Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?..

like image 296
silyevsk Avatar asked Oct 29 '22 18:10

silyevsk


1 Answers

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.

like image 131
JAL Avatar answered Nov 15 '22 05:11

JAL