繁体   English   中英

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

[英]Swift: Cannot assign to immutable expression of type 'AnyObject?!'

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

我即将编写一个 class 来处理更新、添加、获取和删除等解析方法。

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)")
        }
    }

}

由于我现在即将学习swift,我很想得到一个带有一点声明的答案,这样我就可以学到更多。

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

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

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

我这样做有同样的错误:

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

class A {

}

class B: A, MyProtocol {
    var anInt: Int = 0
}

在另一个班级:

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 {...
   ...
}

所以一定要有

protocol MyProtocol: class {

在做这样的铸造时

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

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

要使对象可变,要么在方法声明中添加关键字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
...

使用 AnyObject 关键字解决了我的问题:

protocol UpgradeActionProtocol: AnyObject {
    var upgradeAction: Selector? { get set }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM