1

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?

Daniel Gomez Rico
  • 15,026
  • 20
  • 92
  • 162

1 Answers1

1

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.

cmyr
  • 2,235
  • 21
  • 30
  • 1
    the only possible problem with that approach is that you might end up with an empty dictionary in a place where it would be more useful to understand that userInfo was nil. – cmyr Dec 17 '14 at 17:09