Skip to content

Instantly share code, notes, and snippets.

@CassiusPacheco
Last active May 24, 2020 23:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CassiusPacheco/477af5c133b1c4ce8bd1c72103f0ce7a to your computer and use it in GitHub Desktop.
Save CassiusPacheco/477af5c133b1c4ce8bd1c72103f0ce7a to your computer and use it in GitHub Desktop.
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