Swift 3 array of structs & # 8594; cast to NSObject & # 8594; cast back => crash

The following code crashes on Swift 3, can someone 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 this because in Swift 3, the array of structures is an NSObject (it is not in Swift 2), and it somehow cannot be converted to an NSArray? And why is it NSObject? ..

+5
source share
1 answer

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

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

Not sure why forced downcast is not working. Maybe something scared is happening with NSObject .

+2
source

Source: https://habr.com/ru/post/1258483/


All Articles