Swift:无法分配给'AnyObject?'类型的不可变表达式

Phi*_*nie 11 xcode ios parse-platform swift

我搜索过,但是我找不到熟悉的答案,所以......

我将编写一个类来处理解析方法,如更新,添加,提取和删除.

func updateParse(className:String, whereKey:String, equalTo:String, updateData:Dictionary<String, String>) {

    let query = PFQuery(className: className)

    query.whereKey(whereKey, equalTo: equalTo)
    query.findObjectsInBackgroundWithBlock {(objects, error) -> Void in
        if error == nil {
            //this will always have one single object
            for user in objects! {
                //user.count would be always 1
                for (key, value) in updateData {

                    user[key] = value //Cannot assign to immutable expression of type 'AnyObject?!'

                }

                user.saveInBackground()
            } 

        } else {
            print("Fehler beim Update der Klasse \(className) where \(whereKey) = \(equalTo)")
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

由于我现在即将学习迅速,我很乐意通过一点宣言得到答案,这样我就可以学到更多.

顺便说一句:我后来称这个方法是这样的:

parseAdd.updateParse("UserProfile", whereKey: "username", equalTo: "Phil", updateData: ["vorname":self.vornameTextField!.text!,"nachname":self.nachnameTextField!.text!,"telefonnummer":self.telefonnummerTextField!.text!])
Run Code Online (Sandbox Code Playgroud)

Zpa*_*bor 34

在swift中,很多类型被定义为structs,默认情况下是不可变的.

我这样做有同样的错误:

protocol MyProtocol {
    var anInt: Int {get set}
}

class A {

}

class B: A, MyProtocol {
    var anInt: Int = 0
}
Run Code Online (Sandbox Code Playgroud)

在另一个班级:

class X {

   var myA: A

   ... 
   (self.myA as! MyProtocol).anInt = 1  //compile error here
   //because MyProtocol can be a struct
   //so it is inferred immutable
   //since the protocol declaration is 
   protocol MyProtocol {...
   //and not 
   protocol MyProtocol: class {...
   ...
}
Run Code Online (Sandbox Code Playgroud)

所以一定要有

protocol MyProtocol: class {
Run Code Online (Sandbox Code Playgroud)

在做这样的铸造时

  • 这已更改 - 建议使用 `protocol MyProtocol: AnyObject {` 代替 (2认同)

vad*_*ian 10

错误消息说,您正在尝试更改不可变对象,这是不可能的.

默认情况下,声明为方法参数或闭包中的返回值的对象是不可变的.

要使对象可变,要么var在方法声明中添加关键字,要么添加一行来创建可变对象.

默认情况下,重复循环中的索引变量也是不可变的.

在这种情况下,插入一行以创建可变副本,并将索引变量声明为可变.

在枚举时要小心更改对象,这可能会导致意外行为

...
query.findObjectsInBackgroundWithBlock {(objects, error) -> Void in
    if error == nil {
        //this will always have one single object
        var mutableObjects = objects
        for var user in mutableObjects! {
            //user.count would be always 1
            for (key, value) in updateData {

                user[key] = value
...
Run Code Online (Sandbox Code Playgroud)