Swift optimization level breaks converting NSArray to Array

两盒软妹~` 提交于 2019-12-05 22:28:29

问题


The following (somewhat contrived) code works when Swift Optimization Level is set to None [-Onone] (default for debug):

    let nsa = NSArray(array: ["foo", "bar"])
    let a = nsa as [String]

But the app crashes (crash log) during run-time when set to Fastest [-O] (default for release).

I luckily discovered I can work around the issue by doing this:

    let a = nsa as [AnyObject] as [String]

My question is two-fold:

  1. Could you help me understand why this is happening?
  2. Is there a better way to convert an NSArray to an Array?

UPDATE

This does seem to be a bug. I have not reported it to Apple. If someone else would like to take the time to do so, please do!


回答1:


It seems to be fixed on Xcode Version 6.3.1 (6D1002).

And, not an answer to your original problem but as the new Swift 1.2 introduced, as is a forced cast, now replaced by more explicit as!. You should expect an NSArray to Array<T> where T != AnyObject or NSObject to crash.

You'd better use conditional cast as?. Avoid ! any time it's possible.

let nsa = NSArray(array: ["foo", "bar"])
if let a = nsa as? [String] {
    println("a \(a)")
}


来源:https://stackoverflow.com/questions/27694842/swift-optimization-level-breaks-converting-nsarray-to-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!