Swift: Initializers

Swift: Initializers

This post explores all you need to know about initializers in swift. Please find all relevant code here.

1. Initializers for Structs

  • Default Initialisers: Swift by default provide initializers for structures that provide parameters to initialize all the elements in the structure.

struct Student {

    let firstName: String
    let lastName: String

}

let student1 = Student(firstName: "Christo", lastName: "Kumar")        

  • Custom Initialisers: If we create the custom initializer swift no longer provides the default initializer.

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")        

  • Initializer in Extension: If we want to retain the default initializer the custom initializer needs to be implemented in an extension.

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.

  • Designated Initializer: Primary initializer which initializes all the non-optional members of the class.
  • Convenience Initializer: Apart from the primary initializer we may want to initialize only the subset of non-optional class members. This is done through a convenience initializer which in turn calls the designated initializer.

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")
      }
  }        

  • Failable Initialisers: These are the initializers that may return nil if desired parameters are not passed.

class Department {
    var deptName: String

    init?(_ name: String) {
        if (name.isEmpty) {
            return nil
        }
        deptName = name
    }
    
    convenience init?() {
        self.init("Default")
    }
}        

  • Required Initializers: If we declare an initializer as part of the protocol definition, that initializer becomes the required initializer in all the subclass unless the implementation class is the final class.

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)
    }
}        

要查看或添加评论,请登录

Christo Abhinav Kumar的更多文章

  • Swift: Protocols

    Swift: Protocols

    Please find the GitHub link of all the code here. Protocols are used to create the loosely coupled system.

  • Swift: Connect with API using Async Await

    Swift: Connect with API using Async Await

    The sample code below shows the non-reactive ways to connect with an API endpoint using async-await. The code is a…

社区洞察

其他会员也浏览了