Chapter 16: Protocols


There was another post on here about this section of chapter 16 but its been closed.

I’m not super sure what’s going on here. I understand that the variable accountType is a type of Account, and that its set to BitcoinAccount.

But I though that that .self suffix assigns the Bitcoin account metatype to accountType.

Xcode tells be that the constant account os of type BitcoinAccount but I added an additional constructed variable to Bitcoin account called bitcoin I’m told that account has no member called bitcoin.

So I guess my question is, is the metatype of type that inherits a protocol simply the protocol?

@kampai32 This is quite a tricky one to get right but it definitely all makes sense once you understand what is actually going on under the hood after all.

account is of type BitcoinAccount since it uses the BitcoinAccount class to implement the Account protocol, so the following line of code returns true in this case:

let isBitcoinAccount = account is BitcoinAccount 

The problem over here is that account has access only to the BitcoinAccount class part which implements the Account protocol, so just account.value works properly because of that. You can easily check this out by doing a straightforward cast of account to BitcoinAccount as follows:

let sameBitcoinAccount = account as BitcoinAccount

The above line of code doesn’t compile at all at this point since account is still of type Account under the hood. In order to fix this, simply perform a forced downcast of account to BitcoinAccount like this and you are good to go:

let account = accountType.init(initialAmount: 30) as! BitcoinAccount

Please let me know if you have any other questions or issues about the whole thing when you get a chance. Thank you!

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