Swift Tutorial - Tutorialspoint

(backadmin) #1
super.init(name: name)
}

override convenience init(name: String) {
self.init(name: name, count: 1 )

}

}

When we run the above program using playground, we get the following result:


Planet name is: Mercury
No Planets like that: [No Planets]

Failable Initializer


The user has to be notified when there are any initializer failures while defining a class,
structure or enumeration values. Initialization of variables sometimes become a failure
one due to:


 Invalid parameter values.

 Absence of required external source.

 Condition preventing initialization from succeeding.

To catch exceptions thrown by initialization method, swift produces a flexible initialize
called 'failable initializer' to notify the user that something is left unnoticed while initializing
the structure, class or enumeration members. Keyword to catch the failable initializer is
'init?'. Also, failable and non failable initializers cannot be defined with same parameter
types and names.


struct studrecord {
let stname: String

init?(stname: String) {
if stname.isEmpty {return nil }
self.stname = stname
}
}

let stmark = studrecord(stname: "Swing")
if let name = stmark {
Free download pdf