![](/img/trans.png)
[英]Cannot subscript a value of type [String: AnyObject]? with an index of type String
[英]Cannot subscript a value of [AnyObject]? with an index of type String
在下面的函數中,我試圖通過用戶名在Parse.com的Users
表中找到當前用戶,並添加/更新一個名為salaryMode
的字段值。
以下是我的功能和出現的錯誤:
我看到錯誤 :
無法下標[AnyObject]的值? 索引類型為String
func saveUserSalaryInfo() {
var query = PFQuery(className:"User")
query.whereKey("username", equalTo: PFUser.currentUser()!.username!)
query.findObjectsInBackgroundWithBlock {
(users: [AnyObject]?, error: NSError?) -> Void in
if error != nil {
users["salaryMode"] = self.salaryMode
} else {
// Log details of the failure
//NSLog("Error: %@ %@", error, error.userInfo)
}
}
}
簡短的回答:不,你不能訪問使用String類型的標的數組
長答案:
users: [AnyObject]?
這意味着用戶變量包含一個可選類型。 因此它可以是nil,或者如果有的話,是AnyObject的數組(實際上允許任何東西)。 但這是一個數組:因此基於索引的訪問需要數字。
您對Dictionary感到困惑,后者的語法類似於使用鍵訪問元素的語法
// Array
let array: [String] = ["one", "two", "three"]
array[0] // "one"
array["one"] // error
// Dictionary
let brothers = ["one": "Groucho", "two": "Chico", "three": "Harpo"]
brothers["one"] // Groucho
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.