类型'Any []'的不可变值仅在Swift中具有名为'append'的变异成员,尽管该数组被定义为'var'

Bla*_*ard 17 ios swift

我想在我的数组中附加一个新对象,该数组var在我的Swift应用程序中定义,但是尽管我将其定义为var,但当我尝试追加它时发生了以下错误.

`Immutable value of type 'Any[]' only has mutating members named 'append'`
Run Code Online (Sandbox Code Playgroud)

这是我的代码:

var contactsArray: Any[]!
func popoverWillClose(notification: NSNotification) {
    if popoverTxtName.stringValue != "" && popoverTxtContactInfo.stringValue != "" {
        contactsArray.append(makeDictionaryRecord(popoverTxtName.stringValue, withInfo: popoverTxtContactInfo.stringValue))
    }
}
Run Code Online (Sandbox Code Playgroud)

(makeDictionaryRecord(withInfo:)方法需要两个String并返回Dictionary<String, Any>)

我的原始代码定义contactsArraylet,后来我发现这是我的错误,所以我把它改成了var.然而,到目前为止,事情还没有成功.

我也改变了成分的类型contactsArrayAnyObject[],Any[]AnyObject[]!,但什么也没有改变.

(话虽如此,因为它contactsArray必须Dictionary在其中,它必须被定义为Any[]或者Any[]!,因为我Dictionary被定义为struct,如果我理解正确的话.)

我的代码出了什么问题?如何正确附加组件contactsArray

Nat*_*ook 13

问题1:您已定义contactsArray为隐式展开的Optional,但Optional变量的值始终是不可变的.您可以通过这种方式定义它,以允许附加值:

var contactsArray: [Any]
Run Code Online (Sandbox Code Playgroud)

更新:由于Swift通过可选链接引入了赋值,因此这不是问题.使用隐式解包的选项,这会自动发生.

问题2:你有没有考虑到数组的初始值- 编译器开始抱怨,当你解决问题1的隐式展开可选的,这意味着该值nil,所以你会得到一个运行时异常.解决方案是使用空数组初始化变量:

var contactsArray: [Any]! = []
Run Code Online (Sandbox Code Playgroud)

几乎从不需要一个可选的数组 - 一个空数组就像nil启动"无值"一样好,更安全.如果您决定使用可选数组,请使用常规可选(即声明为?),而不是隐式解包:

var contactsArray: [Any]? = []
Run Code Online (Sandbox Code Playgroud)


Bjo*_*orn 11

数组声明的语法已经改变,现在是

var contractsArray: [Any] = []

此外,如果您将数组修改为结构或枚举的一部分,您可能会看到此错误.struct或enum是值类型,该方法需要mutating关键字:

struct contacts {
    var contactsArray:[Any] = []
    mutating func popoverWillClose(notification: NSNotification) {
        if popoverTxtName.stringValue != "" && popoverTxtContactInfo.stringValue != "" {

            contactsArray.append(makeDictionaryRecord(popoverTxtName.stringValue, withInfo: popoverTxtContactInfo.stringValue))
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

此外,您无法使用let关键字var将变量方法的实例保存为常量,因此需要将其声明为因为调用变异函数时变量的值将更改.