Created
February 10, 2020 17:53
-
-
Save davbeck/a75fb62752aeee1fac18fe66612bc13e to your computer and use it in GitHub Desktop.
Swift friendly wrapper around associated objects.
This file contains hidden or 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
import ObjectiveC | |
extension objc_AssociationPolicy { | |
public static let retain = objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN | |
public static let retainNonatomic = objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC | |
public static let copy = objc_AssociationPolicy.OBJC_ASSOCIATION_COPY | |
public static let copyNonatomic = objc_AssociationPolicy.OBJC_ASSOCIATION_COPY_NONATOMIC | |
public static let assign = objc_AssociationPolicy.OBJC_ASSOCIATION_ASSIGN | |
} | |
public struct AssociatedProperty<T: Any> { | |
fileprivate let key = UnsafeRawPointer(UnsafeMutablePointer<UInt8>.allocate(capacity: 1)) | |
public let policy: objc_AssociationPolicy | |
public init(policy: objc_AssociationPolicy = .retain) { | |
self.policy = policy | |
} | |
} | |
extension NSObjectProtocol { | |
public subscript<T>(property: AssociatedProperty<T>) -> T? { | |
get { | |
return objc_getAssociatedObject(self, property.key) as? T | |
} | |
set { | |
objc_setAssociatedObject(self, property.key, newValue, property.policy) | |
} | |
} | |
public func lazyLoad<T>(_ property: AssociatedProperty<T>, fallback load: () -> T) -> T { | |
if let value = self[property] { | |
return value | |
} else { | |
let value = load() | |
self[property] = value | |
return value | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment