Thor
Thor

Reputation: 10058

Can we add static stored variable via extension, in Swift?

In the book Swift Programming Language 3.0, it says that we can't use extension to add stored property.

I tried it out with instance stored variable and Xcode displayed an error as expected.

But when I tried with static stored variable, everything compiled just fine.

Is there something that I'm missing or doing wrong?

class MyClass {}
extension MyClass {
    static var one: Int {
        return 1
    }
    static var two = 2 //compiled just fine 
}
let myVariable = MyClass()
MyClass.two

Upvotes: 6

Views: 3950

Answers (1)

Jacob King
Jacob King

Reputation: 6157

You can't put stored properties in instances of an extension, you can cheat a little though and get the same effect with Objective-C associated objects. Give the following code a try:

private var associationKey: UInt8 = 0
var validationTypes: ValidationTypes {
        get {
            return objc_getAssociatedObject(self, &associationKey) as? ValidationTypes ?? []
        }
        set(newValue) {
            objc_setAssociatedObject(self, &associationKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
        }
    }

Obviously replacing ValidationTypes as appropriate.

Upvotes: 1

Related Questions