Swift:为什么我的条件绑定不起作用?

时间:2016-02-23 11:34:22

标签: json swift

我从http://pokeapi.co/api/v1/pokemon/1/读取了JSON文件,并将它们存储到 pokemonInfoDict 中。

所以 pokemonInfoDict 的类型为 Dictionary< String,AnyObject>

  

print(pokemonInfoDict [" move"]!)具有以下输出:

(
    {
    "learn_type" = "tutor";
    "name" = "Bind";
    "resource_uri" = "/api/v1/move/20/";
},
    {
    "learn_type" = "machine";
    "name" = "Swords-dance";
    "resource_uri" = "/api/v1/move/14/";
}
)

因此,它是 [Dictionary<字符串,字符串>] 类型

那么为什么我的条件绑定无法将其强制转换为 [Dictionary<字符串,字符串>] 类型? 不调用print(movesArray)。

if let movesArray = pokemonInfoDict["moves"] as? [Dictionary<String,String>] where movesArray.count > 0
{
     print(movesArray)
}

任何帮助将不胜感激。我已经坚持了很长一段时间......

2 个答案:

答案 0 :(得分:3)

试试这个,

if let movesArray = pokemonInfoDict["moves"] as? [[String:AnyObject]] where movesArray.count > 0
{
    print(movesArray)
}

答案 1 :(得分:1)

此代码适用于我:

var p:Dictionary < String, AnyObject > = Dictionary()
var d1:Dictionary < String, String > = Dictionary() // explicit type
d1["learn_type"] = "tutor"
d1["name"] = "bind"
var d2 = ["learn_type":"machine", "name":"dance"] // implied type
p["moves"] = [d1, d2]
if let g = p["moves"] as? [Dictionary < String, String >] {
    print("It works!") // and it does print
}

所以我怀疑你的代码有些奇怪,你应该发布更多的代码。

我根据您更新的答案查看了网址http://pokeapi.co/api/v1/pokemon/1/。确实,加载的大多数数据都具有String类型。但是,使用标准JSON解析:

NSURLSession.sharedSession().dataTaskWithURL(NSURL(string: "http://pokeapi.co/api/v1/pokemon/1/")!) {(data, response, error) in
   let parsed = try? NSJSONSerialization.JSONObjectWithData(data!, options:[])
   // more code here
}

我发现moves数组中的某些词典包含类似

的条目
[level:7]

并且7的类型不是String所以Swift说moves的类型必须是[Dictionary<String,AnyObject>],尽管几乎所有条目都是<String,String> 1}}。以下是一些检查它的代码:

NSURLSession.sharedSession().dataTaskWithURL(NSURL(string: "http://pokeapi.co/api/v1/pokemon/1/")!) {(data, response, error) in
    let parsed = try? NSJSONSerialization.JSONObjectWithData(data!, options:[])
    if let parsed = parsed as? Dictionary<String,AnyObject> {
        if let m2 = (parsed["moves"]) {
            if let m3 = m2 as? [AnyObject] {
                if let m4 = m3 as? [Dictionary<String,AnyObject>] {
                    m4.forEach({m in
                        for (n,v) in m {
                            if let _ = v as? String { }
                            else { print("not a String: \(n):\(v)") }
                        }
                    })
                    print("m4 was ok")
                } else { print("m4 is wrong type") }
            } else { print("m3 is wrong type") }
        } else { print("m2 is wrong type") }
    } else { print("parsed is wrong type") }
}.resume()