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 »

1
  • Please do not change declarations in your post, it's cause problems with written answers. Commented Sep 6, 2016 at 8:40

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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 basically yes. You can use other property in your class (check update). Also this question could be related
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.