Is it possible in Swift to add variables to an object at runtime?

后端 未结 3 2309
温柔的废话
温柔的废话 2020-12-30 16:09

Specifically, I would like to add a variable of type enum to an instance of UIView, without subclassing or create an extension.

Thanks.

3条回答
  •  难免孤独
    2020-12-30 16:39

    Here is a simple but complete example derived from jckarter's answer.

    It shows how to add a new property to an existing class. It does it by defining a computed property in an extension block. The computed property is stored as an associated object:

    import ObjectiveC
    
    // Declare a global var to produce a unique address as the assoc object handle
    var AssociatedObjectHandle: UInt8 = 0
    
    extension MyClass {
        var stringProperty:String {
            get {
                return objc_getAssociatedObject(self, &AssociatedObjectHandle) as String
            }
            set {
                objc_setAssociatedObject(self, &AssociatedObjectHandle, newValue, objc_AssociationPolicy(OBJC_ASSOCIATION_RETAIN_NONATOMIC))
            }
        }
    }
    

提交回复
热议问题