I'm trying to convert the following Objective-C code to Swift. In my Objective-C code, there's a static variable and its accessed from a class method.
@implementation SomeClass
static NSMutableArray *_items;
+ (void)someMethod {
[_items removeAll];
}
@end
Since you can't access types declared like this private var items = [AnyObject]()
from class functions in Swift, I created a stored property for it like this.
class var items: [AnyObject] {
return [AnyObject]()
}
And I'm trying to call a method on it from a class function like so.
class func someFunction() {
items.removeAll(keepCapacity: false)
}
But I get this error Immutable value of type '[AnyObject]' only has mutating members named 'removeAll'.
Can anyone please tell me what's the cause of this error and how to correct it?
Thank you.
Yet the manual for Swift 2 still claims just enumeration ond structures may use static store properities.
With this code:
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
- andremoveAll
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:
If you want to get rid of the
Static
struct every time you refer to theitems
property, just define a wrapper computed property:so that the property can be accessed more simply as:
Updated to Swift1.2
In Swift1.2[Xcode6.3], you can declare static properties using keyword static, also you can declare static methods using keyword class or static.
EDIT:
The difference between
static
andclass
modifier is thatstatic
is just an alias for "class final",so methods modified withstatic
can not be overridden in subclasses.Thanks @Maiaux's