在Swift 2中,如何将JSON数组转换为[Int32]

时间:2016-02-04 07:06:41

标签: ios swift swift2 ios9

我有以下代码在JSON文件中读取,然后将其数组转换为[Float32]或[Int32]

let location = NSString(string:"/Users/myname/Documents/test.js").stringByExpandingTildeInPath
let rawData = NSData(contentsOfFile: location)
let modelData = try? NSJSONSerialization.JSONObjectWithData(rawData!, options: NSJSONReadingOptions.AllowFragments)

let dict = modelData as! NSDictionary
guard let vertices = dict["vertices"] as? [Float32] else {
    print("error casting vertices")
    return
}
guard let indices = dict["faces"] as? [Int32] else {
    print("error casting indices")
    return
}

JSON文件的内容是:

{
    "vertices" : [1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9],
    "faces" : [0,1,2]
}

JSON文件已成功加载和解析,但vertices[Float32]的强制转换成功,而faces[Int32]的强制转换失败。无论如何要将faces投射到[Int32]

2 个答案:

答案 0 :(得分:2)

只需将其转换为[Int]而不是[Int32]。您可以检查类似的类型

dict["faces"] is [Int]

答案 1 :(得分:1)

let indices = dict["faces"] indices数组创建类型为Array<Double>时,您无法将其转换为[Int32]或甚至[Int]。您可以尝试使用以下代码将其转换为[Int32]

let faces = dict["faces"]! as [AnyObject]
let intFaces = (faces as! [Int]).map({Int32($0)})

intFaces的类型为[Int32]