0

I have the following code to read in a JSON file and then cast its arrays to either [Float32] or [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
}

The contents of the JSON file is:

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

The JSON file has been loaded and parsed successfully, however, the cast of vertices to [Float32] succeeds while the cast of faces to [Int32] fails. Is there anyway to cast faces to [Int32]?

Gavin
  • 8,204
  • 3
  • 32
  • 42
shapeare
  • 4,133
  • 7
  • 28
  • 39

2 Answers2

2

Just cast it to [Int] not [Int32]. You can check the type like so

dict["faces"] is [Int]
gasho
  • 1,926
  • 1
  • 16
  • 20
1

When you do let indices = dict["faces"] indices array is created of type Array<Double> thus you can not type cast it as [Int32] or even as [Int]. You can try out following code to convert it to [Int32]

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

intFaces will be of type [Int32]

Vishnu gondlekar
  • 3,896
  • 21
  • 35
  • 1
    looks like the first line of code should be `let faces = dict["faces"] as? [AnyObject]` in Swift 2 – shapeare Feb 04 '16 at 07:53