In Swift, a class or a struct can have multiple initializers which are used to create an instance of that particular type and set up its initial state. The code examples below show how to define a class with single or multiple initializers and how to create an instance of that class.
Single Initializer
class Person { var firstName: String var lastName: String init(firstName: String, lastName: String) { self.firstName = firstName self.lastName = lastName } }
You can instantiate the above class and print Person’s first name like this:
let person = Person(firstName: "Sergey", lastName: "Kargopolov") print(person.firstName)
Multiple Initializers
Let’s add a second initializer to the above Swift class which will accept person’s email address as well.
class Person { var firstName: String var lastName: String var email: String? init(firstName: String, lastName: String) { self.firstName = firstName self.lastName = lastName } init(firstName: String, lastName: String, email: String) { self.firstName = firstName self.lastName = lastName self.email = email } }
To instantiate the above class and print out Person’s first name and email address you can write:
let person = Person(firstName: "Sergey", lastName: "Kargopolov", email: "[email protected]") print(" First name \(person.firstName), email address: \(person.email ?? "") ")