failable initialiser swift simple example
In swift, Failable initialisers are used with structure,class and enumeration. When it is not sure that a property within class or structure or enumeration will be initialised then failable initialisers are used.
For this, we write initialiser with init? syntax and if initialisation succeeds then value is assigned or else nil value is assigned.
Example Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
class FailInit{ let a:String let b:Int init?(a:String,b:Int){ if a.isEmpty { return nil } else{ self.a = a } if b>0 { self.b = b } else{ return nil } } } var failObj = FailInit(a:"",b: 5) failObj?.a //nil var failObj1 = FailInit(a:"Hello",b: 1) failObj1?.a //Hello var failObj2 = FailInit(a:"Hey", b:0) failObj2?.a //nil |