The Madness of Errors in Swift
Let’s take a common scenario. You are making an HTTP request and are checking the response for an error. If there is one, you’d like to post a notification and let some error handler deal with it.
1 2 3 4 5 6 7
Uh oh, there’s a compiler error on the
userInfo argument with the message “Extra argument ‘userInfo’ in call”. Huh?
postNotificationName definitely allows for a
userInfo parameter. Maybe it’s a hidden typing error? According to the docs
userInfo is supposed to be an optional dictionary like of type:
[NSObject : AnyObject]. My key is a String which is bridged from
NSString, which is an
NSError is also an
AnyObject, so what gives?
After banging my head on the wall for a while I remembered that the
error variable from AlamoFire is an optional. Therefore, the correct declaration for
userInfo is to unwrap the error:
And voilà, no more compilation errors.
“Extra argument ‘userInfo’ in call” is a crappy error message. The proper one should have been something about values in the
userInfo dictionary not being optional.
Swift is full of these unfortunately. Between these and your friendly SourceKit crashes it’s getting untenable. My wish for 2015 is for Apple to address these shortcomings.