Arrays of Generics in Swift

前端 未结 5 1196
有刺的猬
有刺的猬 2020-12-13 06:05

I\'ve been playing around with arrays of generic classes with different types. It\'s easiest to explain my problem with some sample code:

// Obviously a very         


        
5条回答
  •  粉色の甜心
    2020-12-13 06:23

    This can be better explained with protocols like Equatable. You cannot declare an array [Equatable] because while two Int instances can be compared to each other and two instances of Double can be compared to each other, you cannot compare an Int to a Double although they both implement Equatable.

    MyProtocol is a protocol, that means it provides a generic interface. Unfortunately, you have also used Self in the definition. That means that every type that conforms to MyProtocol will implement it differently.

    You have written it yourself - Int will have value as var value: Int while a MyObject will have value as var value: MyObject.

    That means that a struct/class that conforms to MyProtocol cannot be used in place of another struct/class that conforms to MyProtocol. That also means that you cannot use MyProtocol in this way, without specifying a concrete type.

    If you replace that Self with a concrete type, e.g. AnyObject, it will work. However, currently (Xcode 6.3.1) it triggers a segmentation error when compiling).

提交回复
热议问题