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

查看:138
本文介绍了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)")
        }
    }

}

此刻我将要学习快速,我希望得到一点声明就可以得到一个答案,这样我就会学到更多.

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:我以后会像这样调用此方法:

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.

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

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天全站免登陆