Morniak Morniak - 1 year ago 94
Swift Question

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 »

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download