How does one create a mutable copy of an immutable array in swift?

arrays, ios, swift

Solution

The problem is that `self.toolbar.items` is an implicitly unwrapped optional (of type [AnyObject]!) and they are always immutable. When you assign to the variable `toolbarItems` without explicitly stating its type, it too becomes an implicitly unwrapped optional, and thus is immutable as well.

To fix this do either:

var toolbarItems:[AnyObject] = self.toolbar.items
toolbarItems.removeAtIndex(2)

Or:

var toolbarItems = self.toolbar.items as [AnyObject]
toolbarItems.removeAtIndex(2)

Update

As of Xcode 6 Beta 5, you can update collections that are stored in optional variables, so the original code now works:

var toolbarItems = self.toolbar.items
toolbarItems.removeAtIndex(2)

Problem

Now that Swift's Array's are truly immutable thanks to full value semantics, how can I create an mutable copy of an immutable array? Similar to Obj-C `mutableCopy()`. I can of course downcast the array to an NSArray and use `mutableCopy()` but don't want to use NSArray because it does not strictly typed. I have a `toolbar` which has `items` from the storyboard. I want to remove an item from the toolbar and use `toolbar.setItems`. I wanted to do it without casting as a `NSArray`, because none of these functions take `NSArrays`, they take `[AnyObject]`. Obviously now when I call `removeAtIndex()` it does not work, which is correct. I just need a mutableCopy Simply assigning to var does not work for me and give '`Immutable value of type [AnyObject]`' ``` var toolbarItems = self.toolbar.items toolbarItems.removeAtIndex(2) //Immutable value of type [AnyObject] ``` I am using Beta 3

Original source