1

I have two protocols and two classes implementing them as following :

protocol IMessage { }

class Message: IMessage { }

protocol IConversation {
    var messages: [IMessage] { get set }
}

class Conversation: IConversation {
    var messages: [Message] = []
}

With this code, I got the error « Type 'Conversation' does not conform to protocol IConversation »

Yury
  • 6,044
  • 3
  • 19
  • 41
Morniak
  • 958
  • 1
  • 12
  • 37
  • Please do not change declarations in your post, it's cause problems with written answers. – Yury Sep 06 '16 at 08:40

2 Answers2

1

Your message types don't match. Your protocol requires messages of a type [IMessage]. You're declaring it in the class with [Message].

dersvenhesse
  • 6,276
  • 2
  • 32
  • 53
1

Problem is in difference between IMessage and Message types. IConversation protocol expect that you are able assign to property messages variable with any type of [IMessage], not only case [Message]. Simple example with one more class:

class OtherMessage: IMessage { }

By protocol declaration you should be able to assign variable with type [OtherMessage] to messages, and class Conversation don't allow this. Fix it:

class Conversation: IConversation {
    var messages: [IMessage] = []
}

Update: if you need to work with Message type, you can use, for example, this solution:

class Conversation: IConversation {
    var messages: [IMessage] {get{return _messages}set{_messages = newValue as! [Message]}}
    var _messages: [Message] = []
}

and work with _messages inside class.

Yury
  • 6,044
  • 3
  • 19
  • 41
  • Thanks for the answer. So if my class `Conversation` is built to work only with `Message`, all I can do is to check the type and throw an error if it's another implementation of `IMessage` ? – Morniak Sep 06 '16 at 08:48
  • @Morniak basically yes. You can use other property in your class (check update). Also [this](http://stackoverflow.com/questions/38007881/swift-protocol-to-require-properties-as-protocol) question could be related – Yury Sep 06 '16 at 08:58