silyevsk silyevsk - 10 months ago 85
Swift Question

swift 3 array of structs -> cast to NSObject -> cast back => crash

The following code crashes on Swift 3, can anyone please explain why?

struct S {
let a:Int

let t = [S(a: 8)]
let u:AnyObject = t as NSObject
let v:[S] = u as! [S]

Is that because in Swift 3 array of structs is NSObject (it's not in Swift 2) and it somehow can't be converted to NSArray well? And why is it NSObject?..

Answer Source

A possible solution would be to use a conditional binding with an optional downcast:

if let v = u as? [S] { /* */ }

Not sure why forced downcast wouldn't work though. Might be something funky going on with NSObject.