5

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
halfer
  • 19,824
  • 17
  • 99
  • 186
Thor
  • 9,638
  • 15
  • 62
  • 137
  • 2
    Yes, you can add a static stored variable, but that is bound to the type `MyClass` and unrelated to a specific instance such as `myVariable`. – Martin R Oct 18 '16 at 07:37
  • 1
    See http://stackoverflow.com/questions/25426780/how-to-have-stored-properties-in-swift-the-same-way-i-had-on-objetive-c for adding properties in extensions via associated objects. – Martin R Oct 18 '16 at 07:40

1 Answers1

1

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.

Jacob King
  • 6,025
  • 4
  • 27
  • 45
  • 1
    It might be worth noting this is Swift 2.3 code, so there may be minor syntaxual changes if you are working in Swift 3.0. – Jacob King Oct 18 '16 at 07:33