Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Simplest Way to Add Stored Property to Swift Extension

DZone 's Guide to

Simplest Way to Add Stored Property to Swift Extension

If you're interested in honing your iOS development skills, check out this Swift code snippet.

· Web Dev Zone ·
Free Resource
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.

The fileprivate access control ensures the variable storedProperty_FILEPRIVATE and storedProperty_DEFAULT are not global.

Of course, you can modify it as per your requirements (e.g. make it read-only, do validation before setting, etc.)

Unfortunately, I haven't found a way to make sure that the property is initialized when an object is instantiated and so we must provide a default value (after the ?? nil coalescing operator) in case we haven't initialized the storedProperty of the object.

If you don't want to provide a default value, you can just do it like below (notice that the return type become Int? instead of Int)

extension ExampleClass {
    var storedProperty: Int? {
        get {return storedProperty_FILEPRIVATE[ObjectIdentifier(self)]}
        set {storedProperty_FILEPRIVATE[ObjectIdentifier(self)] = newValue}
    }
}
Topics:
swift ,ios development ,swift tutorial ,web dev ,stored property

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}