Last active
May 24, 2020 23:36
-
-
Save CassiusPacheco/477af5c133b1c4ce8bd1c72103f0ce7a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public func associatedObject<ValueType: Any>(base: AnyObject, key: UnsafePointer<UInt8>, initializer: () -> ValueType) | |
-> ValueType { | |
// if there is already an associated value returns it | |
if let associated = objc_getAssociatedObject(base, key) as? ValueType { | |
return associated | |
} | |
// associated value not found, initializes closure, makes the association and returns it | |
let associated = initializer() | |
associateObject(base: base, key: key, value: associated) | |
return associated | |
} | |
public func associateObject<ValueType: Any>(base: AnyObject, key: UnsafePointer<UInt8>, value: ValueType) { | |
objc_setAssociatedObject(base, key, value, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) | |
} | |
// Usage example | |
// Add a `someProperty` property to all UIViews | |
private struct AssociatedKeys { | |
static var myKey: UInt8 = 0 | |
} | |
extension UIView { | |
var someProperty: Int { | |
return associatedObject(base: self, key: &AssociatedKeys.myKey, initializer: { () -> Int in | |
return 0 | |
}) | |
} | |
} | |
print(view.someProperty) // prints 0 | |
view.someProperty = 1 | |
print(view.someProperty) // prints 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment