Class does not conform to protocol

时间:2016-07-11 22:14:52

标签: ios swift oop

This is my protocol:

protocol LiveTableViewCellProtocol: class {
    var data: LiveCellObjectProtocol! { get set }
}

This is my class:

class RepliesTableViewCell: UITableViewCell, LiveTableViewCellProtocol {
        var data: RepliesCellObject! //ERROR! does not conform to protocol.
}

RepliesCellObject is defined as:

public class RepliesCellObject: NSObject , LiveCellObjectProtocol{
    //basic stuff here.
}

RepliesCellObject is a LiveCellObjectProtocol ... so why doesn't my table cell conform?

4 个答案:

答案 0 :(得分:3)

It doesn't conform because in an object that conforms to LiveTableViewCellProtocol, you can set data to any LiveCellObjectProtocol, including one that isn't an NSObject. In RepliesTableViewCell, you can't do that. The data must be set to a LiveCellObjectProtocol that is also an NSObject.

Therefore RepliesTableViewCell doesn't conform to LiveTableViewCellProtocol.

答案 1 :(得分:0)

It must specifically be the same as the protocol says. What you're doing is not allowed because it is not the exact same. Remember, you can use as! to make it a RepleisCellObject if you're sure it is.

答案 2 :(得分:0)

associatedtype can help here

protocol LiveTableViewCellProtocol: class {
    associatedtype Data: LiveCellObjectProtocol
    var data: Data! { get set }
}

答案 3 :(得分:0)

You should use associated type

   protocol LiveTableViewCellProtocol: class {
        associatedtype Object : LiveCellObjectProtocol

        var data: Object! { get set }
    }