2016-10-26 17 views
0

私のプロジェクトをswift 3.0にアップデートしようとしていて、サーバからデータを引き出すコードが次のような画像になります。タイプ "Any"はサーバからデータアレイを引き出す際にSwift 3に添字のメンバーがありません

enter image description here

私がここにありますソリューションの多くを試みたが、有用な結果と問題は、この場合には何ですか?

do { 
     let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) 


     if let countries = json["Countries"] as? [String: AnyObject] { 
      for country in countries { 
       if let couname = country["countryname"] as? [AnyObject] { 
        country_names.append(couname) 
       } 

       if let coucode = country["code"] as? [AnyObject] { 
        country_codes.append(coucode) 
       } 

      } 
     } 
    } catch { 
     print("Error Serializing JSON: \(error)") 
    } 

答えて

1

それを使用する前に、[String: Any]jsonをキャストしてみます。

また、あなたはここでエラーを持っているように見える:if let couname = country["countryname"] as? [AnyObject]

あなたは[String: AnyObject]の配列にキャストする必要があります[[String: AnyObject]]

調整後のコードは次のようになります。

do { 
    let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String: Any] 

    if let countries = json["Countries"] as? [[String: AnyObject]] { 
     for country in countries { 
      if let couname = country["countryname"] as? [AnyObject] { 
       country_names.append(couname) 
      } 

      if let coucode = country["code"] as? [AnyObject] { 
       country_codes.append(coucode) 
      } 

     } 
    } 
} catch { 
    print("Error Serializing JSON: \(error)") 
} 
0

let jsonの代わりにこれを使用してください。

guard let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String:AnyObject] else { return } 
+0

私はこの行を試してみました今度は、2つのifステートメントの次の行にエラーが表示されます。 '(key:String、value:AnyObject)'タイプに添字メンバーがありません –

関連する問題