0

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 to animals or dogs).

So there is no risk that writing this animals.append(Animal()) I put an Animal inside the dogs Array. Infact animals and dogs are 2 distinct values. This would not be possible if Array were an Object 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.

Luca Angeletti
  • 58,465
  • 13
  • 121
  • 148

0 Answers0