Daniel Gomez Rico
Daniel Gomez Rico

Reputation: 15945

Custom NSError weird behaviour Swift

In Swift, I have a custom NSError, I need to get the error userInfo dictionary and add things later, but it is nil in the assign line, but then error.userInfo have an object...

With error.userInfo as nil:

class MyError: NSError {

    init(error: NSError) { 
      var newUserInfo = error.userInfo

      ...newUserInfo is nil...
      super.init(...)
    }

}

If I assign it 2 times it works ( I know there's something missing but what?)

init(error: NSError) { 
  var newUserInfo = error.userInfo
  newUserInfo = error.userInfo

  ...newUserInfo now contains a dictionary...
}

Why?

Upvotes: 1

Views: 1023

Answers (1)

cmyr
cmyr

Reputation: 2275

This looks maybe compiler bug-ey to me, but it's hard to tell without seeing more of your code. At any rate, this sort of thing is easier to debug if you use conditional cast. userInfo in swift is a Dictionary<NSObject: AnyObject>?; if you're getting this from a Cocoa API you can do something like:

if let userInfo = error.userInfo as? [NSObject: NSObject] {
    // modify and assign values as necessary
}

this will at least make it clearer where things are breaking.

Upvotes: 1

Related Questions