How to get userInfo from an NSError clause in catch

If I have a throwing method, like this:

func doSomethingWithString(string:String) throws { guard string.characters.count > 0 else { throw NSError(domain: "CustomErrorDomain", code: 42, userInfo: ["foo" : "bar"]) } // Do something with string... } 

Then I will try to call it and read userInfo :

 do { try doSomethingWithString("") } catch let error as NSError { print(error.domain) print(error.code) print(error.userInfo) } 

... it returns as an empty dictionary (but the domain and code are correctly filled in):

 CustomErrorDomain 42 [:] 

But if I add this extra step:

 do { try doSomethingWithString("") } catch let e { let error = e as NSError print(error.domain) print(error.code) print(error.userInfo) } 

... it works:

 CustomErrorDomain 42 [foo: bar] 

Does anyone know why this could be?

FYI - I'm on Xcode 7 beta 2 (7A121l)

+7
swift swift2 error-handling
source share
1 answer

This is a bug fixed in Xcode 7 Beta 4. Here are excerpts from the release notes ( PDF , p. 15):

Resolved issues in Xcode 7 beta 4 - Swift 2.0 and Objective-C

When throwing a reference to an instance of NSError in Swift, Swift runtime no longer loses the userInfo of the original NSError if it is caught as NSError. The fast runtime now preserves the identity of the original NSError. For example, this statement now holds:

  let e = NSError(...) do { throw e } catch let e2 as NSError { assert(e === e2) } 
+2
source share

All Articles