簡體   English   中英

在Swift 2中,如何將JSON數組強制轉換為[Int32]

[英]In Swift 2, how to cast a JSON array to [Int32]

我有以下代碼可讀取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]

let indices = dict["faces"]將創建類型為Array<Double> indices數組,因此無法將其[Int32][Int32]或什至[Int] 您可以嘗試以下代碼將其轉換為[Int32]

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

intFaces的類型為[Int32]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM