2017-03-17 61 views
-1

当只在真正的iPhone上构建时,目前收到错误“模糊使用'下标''”。使用模拟器时没有任何问题。这里是我的代码:模糊使用“下标”Swift 3编译错误

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) 
       } 
      } 
     } 
+0

我想问题可能来自[String:AnyObject]。我不是Swift专家,但是通过阅读,我获得了有关类似场景的一些信息。检查了这个http://stackoverflow.com/questions/33642059/ambiguous-use-of-subscript-in-swift或甚至http://stackoverflow.com/questions/33592699/ambiguous-use-of-subscript-xcode- 7-1 – Balanced

+0

究竟哪一行?let aObject = arrJSON [index] as! [String:AnyObject]''我想这是因为你没有告诉编译器'arrJSON'是一个数组,所以你不能'arrJSON [index]'。 – Larme

+0

This line: let aObject = arrJSON [index] as! [字符串:AnyObject]。 我怎么知道arrJSON是一个数组? –

回答

0

首先,Swift 3中的JSON字典类型是[String:Any]

ambiguous use原因是编译器不知道allContacts["data"]的类型。这显然是一个数组,但你需要告诉编译器。请不要在Swift中使用基于循环的丑陋C风格索引。如果在重复循环中需要indexobject,请使用enumerated()

if let arrJSON = allContacts["data"] as? [[String : Any]] { 
    for aObject in arrJSON { 
     if ChooseSubject.mineFagKoder.contains(aObject["subject"] as! String) { ...