怎样才能创建一个快捷不变数组的一个可变副本? [英] How does one create a mutable copy of an immutable array in swift?

查看:120
本文介绍了怎样才能创建一个快捷不变数组的一个可变副本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在,斯威夫特的Array的是真正不变的感谢全值语义,我怎么可以创建一个不可变的数组的可变副本?类似的OBJ-C mutableCopy()。我可以在阵列当然向下转换一个NSArray并使用 mutableCopy(),但不希望使用NSArray的,因为它没有严格的类型。

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.

我 A 工具栏里面有项目从故事板。我想从工具栏中删除的项目,并使用 toolbar.setItems 。我想这样做而无需进行转换为的NSArray ,因为没有这些功能需要 NSArrays ,他们采取 [AnyObject]

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].

显然现在当我称之为 removeAtIndex()这是行不通的,这是正确的。我只是需要一个mutableCopy

Obviously now when I call removeAtIndex() it does not work, which is correct. I just need a mutableCopy

简单地分配给VAR我不工作,并给予类型的不可变的值[AnyObject]

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]

我使用Beta 3的

I am using Beta 3

推荐答案

的问题是, self.toolbar.items 是一个隐含解开可选的(类型[AnyObject] !),他们总是一成不变。当你赋予变量 toolbarItems 没有明确说明它的类型,它也成为一个隐解开可选的,因而是不可变的为好。

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.

要解决此问题请执行:

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

或者

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

更新

由于X code 6测试版5,您可以更新存储在可选变量的集合,所以原来的code现在工作:

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)

这篇关于怎样才能创建一个快捷不变数组的一个可变副本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆