swift协议,IBOutlet属性不能具有非对象类型
问题描述:
我想在IB中连接一个自定义的swift委托。委托是一个在swift中实现某个协议的对象。
I would like to wire up a custom swift delegate in IB. The delegate is an object that implements a certain protocol in swift.
protocol ThumbnailTableViewCellDelegate {
func cellWasTouched(thumbnail: Bool, cell: UITableViewCell)
}
class ThumbnailTableViewCell: UITableViewCell {
@IBOutlet var thumbnailTableViewCellDelegate: ThumbnailTableViewCellDelegate?
}
不幸的是,编译器抱怨:
unfortunately, the compiler complains with:
error: 'IBOutlet' property cannot have non-object type 'ThumbnailTableViewCellDelegate'
@IBOutlet var thumbnailTableViewCellDelegate: ThumbnailTableViewCellDelegate?
^~~~~~~~~
答
您必须将 ThumbnailTableViewCellDelegate
协议声明为 @objc
:
@objc protocol ThumbnailTableViewCellDelegate {
func cellWasTouched(thumbnail: Bool, cell: UITableViewCell)
}
这是因为 @IBOutlet
将变量声明为 weak
,仅适用于对象。我不确定为什么你不能说协议符合 AnyObject
,也许这是一个Swift bug。
This is because @IBOutlet
declares the variable as weak
, which only works with objects. I'm not sure why you can't just say the protocol conforms to AnyObject
, perhaps that's a Swift bug.