[英]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.