@cmoyc,
I hope you have seen the video and have some idea of what they are.
Here’s a summary crash course,
when you create a class
class Student {
var name: String
var age: Int
}
To be able to create an instance, you need to have an initialiser, this initialiser must initialise all the properties (that are not optional or have default values)
class Student {
var name: String
var age: Int
init(name: String, age: Int) {
self.name = name
self.age = age
}
}
So now we have an initialiser this is the default or the designated initialiser. Each time we need to create a student object, this is the one that we will call.
A convenience initialiser is one that takes fewer or different parameters and instantiates the object and is tagged with the keyword convenience in front of it.
so we create the class as
class Student {
var name: String
var age: Int
init(name: String, age: Int) {
self.name = name
self.age = age
}
convenience init(name: String) {
self.init(name:name, age:18)
}
}
and in a playground try this as
let john = Student(name:"John", age:42)
let jane = Student(name: "Jane")
print(john.age, jane.age)
Now let us add a new way to create a student, from a JSON dictionary
class Student {
var name: String
var age: Int
init(name: String, age: Int) {
self.name = name
self.age = age
}
convenience init(name: String) {
self.init(name:name, age:18)
}
convenience init?(json: [String:Any]) {
// Convert the JSON into variables to use
if let _name = json["name"] as? String,
let _age = json["age"] as? Int {
self.init(name:_name, age:_age)
return
}
return nil
}
}
let john = Student(name:"John", age:42)
let jane = Student(name: "Jane")
let jsonCode:[String: Any] = ["name":"Jay", "age":99]
print(john.age, jane.age)
if let jay = Student(json: jsonCode) {
print(jay.name, jay.age)
}
and yes, you will realise that as your code gets complex, you might have the need to write convenience initialisers.
cheers,
Jayant