Created
February 19, 2025 19:16
-
-
Save IanKeen/8501c7380b8942d295d8fee24c721f93 to your computer and use it in GitHub Desktop.
Support stored properties in extensions
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
extension SomeUIView { | |
var someProperty: SomeType? { | |
get { self[dynamic: #function] } | |
set { self[dynamic: #function] = newValue } | |
} | |
} |
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
public protocol DynamicProperties: AnyObject { | |
subscript<T>(dynamic key: String) -> T? { get set } | |
} | |
private extension String { | |
var unsafePointer: UnsafeRawPointer { | |
return UnsafeRawPointer(bitPattern: hashValue)! | |
} | |
} | |
extension DynamicProperties { | |
public subscript<T>(dynamic key: String) -> T? { | |
get { return objc_getAssociatedObject(self, key.unsafePointer) as? T } | |
set { objc_setAssociatedObject(self, key.unsafePointer, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } | |
} | |
public subscript<T>(dynamic key: String, or `default`: @autoclosure () -> T) -> T { | |
if let existing: T = self[dynamic: key] { | |
return existing | |
} else { | |
let value = `default`() | |
self[dynamic: key] = value | |
return value | |
} | |
} | |
} | |
extension NSObject: DynamicProperties { } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment