Morniak
Morniak

Reputation: 998

Protocol implementation and inheritance

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 »

Upvotes: 1

Views: 61

Answers (2)

Yury
Yury

Reputation: 6114

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.

Upvotes: 1

dersvenhesse
dersvenhesse

Reputation: 6404

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

Upvotes: 1

Related Questions