protocol MyProtocol { }
var handle: UInt8 = 0
extension MyProtocol {
var myField: Any? {
get {
return objc_getAssociatedObject(self, &handle)
}
set {
objc_setAssociatedObject(self, &handle, newValue, .OBJC_ASSOCIATION_RETAIN)
}
}
}
struct MyObject: MyProtocol {} // works if 'struct' is changed to 'class'
var myObject = MyObject()
myObject.myField = "123456"
myObject.myField // nil
是否有任何方法可以将关联对象与'struct'一起使用,或者是否允许在协议扩展中定义字段而不在'struct'本身中定义字段?