我有以下代码读取 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]
?
最佳答案
只需将其转换为 [Int] 而不是 [Int32]。您可以像这样检查类型
dict["faces"] is [Int]
关于ios - 在 Swift 2 中,如何将 JSON 数组转换为 [Int32],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35194592/