Skip to content

Instantly share code, notes, and snippets.

@bsneed
Created December 9, 2023 23:51
Show Gist options
  • Save bsneed/ec60487ce79492263ac255a9032387e9 to your computer and use it in GitHub Desktop.
Save bsneed/ec60487ce79492263ac255a9032387e9 to your computer and use it in GitHub Desktop.
Swift - Store properties in an extension
import Foundation
internal class StoredExtensionPropertyData {
internal static var storedExtensionProperties = [ObjectIdentifier: StoredExtensionPropertyData]()
var properties = [String: Any]()
}
internal protocol ExtensionProperties: AnyObject {
func get<T>(key: String, owner: ExtensionProperties) -> T?
func set<T>(key: String, value: T?, owner: ExtensionProperties)
//func extensionPropertyCleanup()
}
internal extension ExtensionProperties {
@inlinable
func get<T>(key: String, owner: ExtensionProperties) -> T? {
let store = StoredExtensionPropertyData.storedExtensionProperties[ObjectIdentifier(owner)]
return store?.properties[key] as? T
}
@inlinable
func set<T>(key: String, value: T?, owner: ExtensionProperties) {
let store = StoredExtensionPropertyData()
store.properties[key] = value
StoredExtensionPropertyData.storedExtensionProperties[ObjectIdentifier(owner)] = store
}
func storedPropertyCleanup() {
StoredExtensionPropertyData.storedExtensionProperties.removeValue(forKey: ObjectIdentifier(self))
}
}
class MyClass {
let doWop: String
init() {
self.doWop = "doo doo do dooo wop"
}
deinit {
storedPropertyCleanup()
}
}
extension MyClass: ExtensionProperties {
var hansen: Int? {
get { return get(key: "hansen", owner: self) }
set(value) { set(key: "hansen", value: value, owner: self)}
}
}
let mc = MyClass()
print(mc.doWop)
mc.hansen = 42
print(mc.hansen)
// manually call property cleanup so we can see it disappear.
mc.storedPropertyCleanup()
print(mc.hansen)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment