我有以下代码在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]
?
答案 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]