Swift:无法分配给“AnyObject?!"类型的不可变表达式 [英] Swift: Cannot assign to immutable expression of type 'AnyObject?!'

查看:18
本文介绍了Swift:无法分配给“AnyObject?!"类型的不可变表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I searched, but I didn't find a familiar answer, so...

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

I am about to program a class to handle parse methods like updating, adding, fetching and deleting.

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,我很想通过一个小小的声明得到答案,这样我就可以学到更多.

As I am about to learn swift at the moment, I would love to get an answer with a little declaration, so that I would learn a little bit more.

顺便说一句:我后来这样调用这个方法:

btw: I later call this method like this:

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

推荐答案

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

The error message says, you're trying to change an immutable object, which is not possible.

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

Objects declared as method parameters or return values in closures are immutable by default.

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

To make the object mutable either add the keyword var in the method declaration or add a line to create a mutable object.

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

Also index variables in repeat loops are immutable by default.

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

In this case a line is inserted to create a mutable copy and the index variable is declared as mutable.

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

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

这篇关于Swift:无法分配给“AnyObject?!"类型的不可变表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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