× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS
Antonio Bello
Mar 01, 2015
<p>With this code:</p> <pre><code>class var items: [AnyObject] { return [AnyObject]() } </code></pre> <p>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 <code>[AnyObject]</code> is created, so whatever you add to it, it's lost as soon as its reference goes out of scope.</p> <p>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 <code>mutating</code> - and <code>removeAll</code> is one of them. The reason why it is immutable is because you have defined a getter, but not a setter.</p> <p>Currently Swift classes don't support static properties, but structs do - the workaround I often use is to define an inner struct:</p> <pre><code>class SomeClass { struct Static { static var items = [AnyObject]() } } SomeClass.Static.items.append("test") </code></pre> <p>If you want to get rid of the <code>Static</code> struct every time you refer to the <code>items</code> property, just define a wrapper computed property:</p> <pre><code>class var items: [AnyObject] { get { return Static.items } set { Static.items = newValue } } </code></pre> <p>so that the property can be accessed more simply as:</p> <pre><code>SomeClass.items.append("test") </code></pre> <p>This tip was originally posted on <a href="http://stackoverflow.com/questions/26567480/Static%20properties%20in%20Swift/26567571">Stack Overflow</a>.</p>

Get New Tutorials Delivered to Your Inbox

New tutorials will be sent to your Inbox once a week.

comments powered by Disqus