Swift Initialization





Swift has introduced new type of variables called Optional. These are used to hold nil value in swift. Because of these variable, there are some changes regarding initialization of variables. Here are details for the same:

  1. It is must to have initializer in swift if using non-optional property.


  2. You need to UnWrap optional variables before using them:
















3. If Property can be nil then use ? after property, before setting any value:


4. If you unwrap the property while declaring, then you can use it directly. Please note that it is not considered as good practice as it may cause crash at run time.



5.  With Swift new version, you need to implement initWithCoder method if using init method.


6. Before accessing self properties ( eg view), you must call super class method during init and initWithCoder.


7.  You can create object before calling super method and after that can assign values to that object:


8.  You can create lazy properties, in Lazy properties you can assign values while declaring, but assign statement will be executed whenever we will use that property.  

Please note that Lazy property should always use var instead of let because constant must have value before initialization.


9.  You can add any logic in lazy properties using Closure.


You can even call class OR instance method in lazy properties



10. If defining any custom Initializer, Swift differentiate them as convenience initializer. It is must to call any default initializer ( designated initializer ) from convenience  initializer.



Need to fix as given below:








Comments

Popular posts from this blog

#2 Simple Spring Rest Api with JDBC connection

#1 My First Rest API With Spring Boot Freamwork