Is this interpretation of the code snippet of chapter 16 correct?

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

Account is a protocol. The .Type would say that accountType must be a random type conforming to Account. The BitcoinAccount conforms so the type can be assigned to accountType. This is not an instance of BitcoinAccount yet. This instance of BitcoinAccount is created with accountType.init being account or transferAccount. The variable accountType as thus can hold any type conforming to Account in this case BitcoinAccount. It will never hold an instance. The code above transferred Bitcoins from one account to another. Yet does not explain the need of .Type. You easily could have instantiated two BitcoinAccount objects with
let account = BitcoinAccount.init(initialAmount: 30.00)
let transferAccount = BitcoinAccount.init(transferAccount: account)!

Its use becomes clearer introducing another crypto currency fi Ether. One could make it conform to Account. Once this is done we could transfer our Bitcoins to an Ether Account with following code.
var accountType: Account.Type = BitcoinAccount.self
let account = accountType.init(initialAmount: 30.00)
accountType = EtherAccount.self
let transferAccount = accountType.init(transferAccount: account)!

Yes, I think that is right. Account.Type is a concrete type that conforms to Account. I believe the point here is to show how init can be part of a existential protocol. That gives you another level of indirection as you noted.

This topic was automatically closed after 166 days. New replies are no longer allowed.