Simplest Way to Add Stored Property to Swift Extension

class ExampleClass {}

fileprivate var storedProperty_FILEPRIVATE: [ObjectIdentifier:Int] = [:]
fileprivate var storedProperty_DEFAULT: Int = 0
extension ExampleClass {
var storedProperty: Int {
get {return storedProperty_FILEPRIVATE[ObjectIdentifier(self)] ?? storedProperty_DEFAULT}
set {storedProperty_FILEPRIVATE[ObjectIdentifier(self)] = newValue}
}
}

let a = ExampleClass()
let b = ExampleClass()
print(a.storedProperty) //0
b.storedProperty = 2
a.storedProperty = 1
print(a.storedProperty) //1
print(b.storedProperty) //2
That’s it. Now you can keep the variable definition close to where it’s used (in the extension, instead of in the class definition).
You just add two fileprivate variables or constants and access it in the extension using the computed variable.

Link: https://dzone.com/articles/simplest-way-to-add-stored-property-to-swift-exten?utm_medium=feed&utm_source=feedpress.me&utm_campaign=Feed%3A+dzone%2Fwebdev