Initializers in protocols

While protocols themselves can’t be initialized, they can declare initializers that conforming types should have:

protocol Account {

var value: Double { get set } init(initialAmount: Double) init?(transferAccount: Account)

}

In the Account protocol above, you define two initializers as part of the protocol. This behaves much as you might expect, in that any type that conforms to Account is required to have these initializer.

Although enforcing initializers in protocols can be useful, they also let you create an instance of a type that conforms to that protocol:

class BitcoinAccount: Account { var value: Double

required init(initialAmount: Double) { value = initialAmount

}

required init?(transferAccount: Account) { guard transferAccount.value > 0.0 else {

return nil

}

value = transferAccount.value

}

}

var accountType: Account.Type = BitcoinAccount.self let account = accountType.init(initialAmount: 30.00)

let transferAccount = accountType.init(transferAccount: account)!

This brief example dips a bit into generic programming, which you will learn more about in the next chapter.

results matching ""

    No results matching ""