【问题标题】:In Swift 2, how to cast a JSON array to [Int32]在 Swift 2 中,如何将 JSON 数组转换为 [Int32]
【发布时间】:2016-05-13 16:27:07
【问题描述】:

我有以下代码要读入 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]

【问题讨论】:

    标签: ios swift swift2 ios9


    【解决方案1】:

    只需将其转换为 [Int] 而不是 [Int32]。你可以像这样检查类型

    dict["faces"] is [Int]
    

    【讨论】:

    • 仅供参考,Int和Int32有什么区别?
    • 这家伙解释的很好here
    • 我建议的其他方法是使用 swift 的字典 - [String: AnyObject]
    【解决方案2】:

    当您执行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]

    【讨论】:

    • 看起来第一行代码在 Swift 2 中应该是 let faces = dict["faces"] as? [AnyObject]
    猜你喜欢
    • 2016-12-22
    • 2015-08-20
    • 1970-01-01
    • 2020-01-12
    • 2017-05-04
    • 1970-01-01
    • 2015-03-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多