1

enter image description here

i tried to found out what made this happened, but i failed, is there something wrong?

did anybody else encounter the error like this?

how can i do for that, i need help

this is my code:

protocol MyProtocol {

}

struct MyStruct: MyProtocol {

}


let structs = [MyStruct(), MyStruct()]

var protocols = [MyProtocol]()

protocols = structs // it's ok

protocols += structs // this got an error
Nirav D
  • 71,513
  • 12
  • 161
  • 183
jeffrey
  • 183
  • 1
  • 12

1 Answers1

3

There's compiler magic that happens on this line:

protocols = structs

which loops over the structs, boxing each one into a protocol container, and then doing the assignment. It essentially performs this operation:

protocols = structs.map{ $0 as MyProtocol }

or equivalently:

protocols = structs as [MyProtocol]

This compiler magic isn't applied for the += operator. You can do it yourself, though:

protocols += structs as [MyProtocol]
Alexander
  • 59,041
  • 12
  • 98
  • 151