gpt4 book ai didi

ios - 无法分配给此表达式的结果 - 字典

转载 作者:行者123 更新时间:2023-11-29 01:51:05 25 4
gpt4 key购买 nike

我真的很困惑。

我找到了有关如何使用字典的示例,但没有找到解释此错误的示例。

这是我的代码。

struct GDuserSettings{
var GDUserSettings = Dictionary<String, Bool>()
func getSettings(user: PFUser){
var settingsquery = PFQuery(className: "ProfileSettings")
settingsquery.whereKey("user", equalTo: user)
settingsquery.getFirstObjectInBackgroundWithBlock{(object: PFObject?, error:NSError?) -> Void in
self.GDUserSettings["location"] = false
//self.userDefaults["pushNotifications"] = object?.objectForKey("pushNotifications")
//self.userDefaults["distanceInMiles"] = object?.objectForKey("distanceInMiles")
}
}
}

有人可以解释为什么我无法分配新的键和值吗?

最佳答案

您应该将 getSettings 更改为:

mutating func getSettings(user: PFUser) {
// ...
}

在 Swift 中 struct 是一个值类型,除非指定 mutating 关键字,否则它上面的方法不允许更改它。

Structures and enumerations are value types. By default, the properties of a value type cannot be modified from within its instance methods.

However, if you need to modify the properties of your structure or enumeration within a particular method, you can opt in to mutating behavior for that method. The method can then mutate (that is, change) its properties from within the method, and any changes that it makes are written back to the original structure when the method ends. The method can also assign a completely new instance to its implicit self property, and this new instance will replace the existing one when the method ends.

参见:The Swift Programming Language ,“方法”一章,“从实例方法内修改值类型”部分

关于ios - 无法分配给此表达式的结果 - 字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31403572/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com