Static properties in Swift

With this code:

class var items: [AnyObject] {
    return [AnyObject]()
}

you are not creating a stored property – instead it’s a computed property, and the worst part is that every time you access to it, a new instance of [AnyObject] is created, so whatever you add to it, it’s lost as soon as its reference goes out of scope.

As for the error, the static computed property returns an immutable copy of the array that you create in its body, so you cannot use any of the array method declared as mutating – and removeAll is one of them. The reason why it is immutable is because you have defined a getter, but not a setter.

Currently Swift classes don’t support static properties, but structs do – the workaround I often use is to define an inner struct:

class SomeClass {
    struct Static {
        static var items = [AnyObject]()
    }
}

SomeClass.Static.items.append("test")

If you want to get rid of the Static struct every time you refer to the items property, just define a wrapper computed property:

class var items: [AnyObject] {
    get { return Static.items }
    set { Static.items = newValue }
}

so that the property can be accessed more simply as:

SomeClass.items.append("test")

Leave a Comment