简体   繁体   中英

Class does not conform to protocol

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?

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.

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.

associatedtype can help here

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

You should use associated type

   protocol LiveTableViewCellProtocol: class {
        associatedtype Object : LiveCellObjectProtocol

        var data: Object! { get set }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM