使用'objc_setAssociatedObject'和'struct'(Swift 3)

时间:2017-08-16 11:50:01

标签: swift

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'本身中定义字段?

0 个答案:

没有答案