Swift: Initializers
This post explores all you need to know about initializers in swift. Please find all relevant code here.
1. Initializers for Structs
struct Student {
let firstName: String
let lastName: String
}
let student1 = Student(firstName: "Christo", lastName: "Kumar")
struct Car {
let make: String
let model: String
//Custom Initialiser
init(_ make: String) {
self.make = make
self.model = "base"
}
}
//default initialiser is GONE, if we provide custom initialiser
let car1 = Car("BMW")
领英推荐
struct Employee {
let firstName: String
let lastName: String
let department: String
}
extension Employee {
init(first: String, last: String) {
self.firstName = first
self.lastName = last
department = "Default"
}
}
//Benefit is both Custom and Default Initialisers are present
let emloyee1 = Employee(first: "Christo", last: "Kumar")
let employee2 = Employee(firstName: "Ayaan", lastName: "Kumar", department: "Diver")
2. Initializers for Classes: Unlike the structures class does not provide default initializers.
class Person {
var firstName: String
var lastName: String
var gender: String
/* Designated Initializer - It must initialise all the non optional members of the class */
init(_ first: String, _ last: String, _ gender: String) {
self.firstName = first
self.lastName = last
self.gender = gender
}
/*Convenience Init - It internally calls the designated initialisers with default parameter */
convenience init(_ first: String, _ last: String) {
self.init(first, last, "default")
}
}
class Department {
var deptName: String
init?(_ name: String) {
if (name.isEmpty) {
return nil
}
deptName = name
}
convenience init?() {
self.init("Default")
}
}
protocol AccountProto {
var custName: String {get}
init (_ name: String)
}
class Account: AccountProto {
var custName: String
var balance: Int
init(_ name: String, _ balance: Int) {
self.custName = name
self.balance = balance
}
required convenience init (_ name: String) {
self.init(name, 0)
}
}