【问题标题】:Swift: Cannot assign to immutable expression of type 'AnyObject?!'Swift:无法分配给“AnyObject?!”类型的不可变表达式
【发布时间】:2015-11-12 15:30:37
【问题描述】:

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

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

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!])

【问题讨论】:

    标签: ios xcode swift parse-platform


    【解决方案1】:

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

    我在这样做时遇到了同样的错误:

    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 {
    

    在进行此类转换时

    【讨论】:

    • 不错的发现 - 为我节省了很多时间。
    • 已更改 - 建议改用protocol MyProtocol: AnyObject {
    • 这是我发现的唯一合理的解释。谢谢!!
    • @ZpaceZombor:谢谢你的cmets解决了我的问题:)
    【解决方案2】:

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

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

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

    【讨论】:

    • 它还会影响重复循环中的索引变量。我改了帖子
    猜你喜欢
    • 2016-08-02
    • 2017-05-16
    • 1970-01-01
    • 1970-01-01
    • 2017-04-14
    • 1970-01-01
    • 2023-03-30
    • 1970-01-01
    • 2023-04-10
    相关资源
    最近更新 更多