Ok, let me better explain what I mean.
Array and Classes
Let's say I have these 2 classes:
class Animal { }
class Dog: Animal { }
I CAN now write the following code and the compiler is totally happy.
var animals = [Animal]()
let dogs = [Dog]()
animals = dogs
This is possible because in Swift Array is a Struct, so it's a value type and therefore the
dogs
array is copied (at least at conceptual level untill a change is made toanimals
ordogs
).So there is no risk that writing this
animals.append(Animal())
I put anAnimal
inside thedogs
Array. Infactanimals
anddogs
are 2 distinct values. This would not be possible ifArray
were anObject
like in Java.
Let's try with protocols!
Let's now define Animal
and Dog
like protocols
protocol Animal { }
protocol Dog: Animal { }
Now this code makes the compiler pretty unhappy
var animals = [Animal]()
let dogs = [Dog]()
animals = dogs
^ error: cannot assign value of type '[Dog]' to type '[Animal]'
Can you explain me why this is NOT possible?
I am using Swift 2.2.