7

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!

13
  • Side note: similar situation for converting NSMutableArray to Array: dev.eltima.com/post/96538497489/… Commented Dec 29, 2014 at 19:33
  • What do you mean "breaks"? What messages are produced? Commented Dec 29, 2014 at 19:34
  • @HotLicks the app crashes when it gets to that code. Ummm... let me find out... please hold... Commented Dec 29, 2014 at 19:36
  • @HotLicks Ok, I added a link to the crash log. Commented Dec 29, 2014 at 19:43
  • 1
    Still an issue with todays release of Xcode 6.2. Thanks a ton for the workaround you have found. In our case I found it would interestingly work when we add NSLog("%@", nsa) (to stay with your example) right behind the declaration. But as soon as that line was removed it crashed. stackoverflow.com/questions/29003323/… Commented Mar 12, 2015 at 11:53

1 Answer 1

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)")
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.