I've seen a few people getting confused between Integer (a protocol) and Int (a type) in Swift. I think I understand the difference between them, and I get why you can't add Integers together—it doesn't make sense to add two protocols.
However, I'm wondering why this works at all:
var x:Integer = 3
println(x) // Prints 3
If Integer is just a protocol, how come it can store and retrieve an integer value? (And wouldn't it lead to less confusion among Swift beginners if it didn't work?)
Any variable can use a protocol as it's type if all you need is something that conforms to that protocol.
So the int value 3 which you're assigning is being put into a variable where only things (methods, operators, properties, etc) specified in the Integer protocol are available.
This is useful for things like delegates where you don't really care what the concrete type of an object is, as long as it supports the functionality you need (as specified in your protocol)
This is covered in some depth in the "Protocols as Types" section (Protocols chapter) of the swift book
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With