'subscript' Swift 3 编译错误的二义性使用
Ambiguous use of 'subscript' Swift 3 compile error
当前仅在真实 iPhone 上构建时出现错误 "Ambiguous use of 'subscript'"。使用模拟器时没有任何问题。这是我的代码:
let url=URL(string:myUrl)
do {
let allContactsData = try Data(contentsOf: url!)
let allContacts = try JSONSerialization.jsonObject(with: allContactsData, options: JSONSerialization.ReadingOptions.allowFragments) as! [String : AnyObject]
if let arrJSON = allContacts["data"] {
for index in 0...arrJSON.count-1 {
let aObject = arrJSON[index] as! [String : AnyObject]
if(ChooseSubject.mineFagKoder.contains(aObject["subject"] as! String)){
ids.append(aObject["id"] as! String)
names.append(aObject["name"] as! String)
subjects.append(aObject["subject"] as! String)
descriptions.append(aObject["description"] as! String)
deadlines.append(aObject["deadline"] as! String)
}
}
}
首先Swift3中的JSON字典类型是[String:Any]
.
ambiguous use
原因是编译器不知道allContacts["data"]
的类型。它显然是一个数组,但你需要告诉编译器。请不要在 Swift 中使用丑陋的基于 for 循环的 C 风格索引。如果在重复循环中需要 index
和 object
,请使用 enumerated()
.
if let arrJSON = allContacts["data"] as? [[String : Any]] {
for aObject in arrJSON {
if ChooseSubject.mineFagKoder.contains(aObject["subject"] as! String) { ...
当前仅在真实 iPhone 上构建时出现错误 "Ambiguous use of 'subscript'"。使用模拟器时没有任何问题。这是我的代码:
let url=URL(string:myUrl)
do {
let allContactsData = try Data(contentsOf: url!)
let allContacts = try JSONSerialization.jsonObject(with: allContactsData, options: JSONSerialization.ReadingOptions.allowFragments) as! [String : AnyObject]
if let arrJSON = allContacts["data"] {
for index in 0...arrJSON.count-1 {
let aObject = arrJSON[index] as! [String : AnyObject]
if(ChooseSubject.mineFagKoder.contains(aObject["subject"] as! String)){
ids.append(aObject["id"] as! String)
names.append(aObject["name"] as! String)
subjects.append(aObject["subject"] as! String)
descriptions.append(aObject["description"] as! String)
deadlines.append(aObject["deadline"] as! String)
}
}
}
首先Swift3中的JSON字典类型是[String:Any]
.
ambiguous use
原因是编译器不知道allContacts["data"]
的类型。它显然是一个数组,但你需要告诉编译器。请不要在 Swift 中使用丑陋的基于 for 循环的 C 风格索引。如果在重复循环中需要 index
和 object
,请使用 enumerated()
.
if let arrJSON = allContacts["data"] as? [[String : Any]] {
for aObject in arrJSON {
if ChooseSubject.mineFagKoder.contains(aObject["subject"] as! String) { ...