Swift v2 Error Handling: Shadowing the method that throws...

Gentlefolk,


Swift v2 try-catch mechanisms maps onto Objective-C quite well. Except when there is a shadowing problem.


For example:


- (nullable NSDictionary *) dataForKey: (NSString *) key error: (NSError * __nullable __autoreleasing *)error;


which maps into Swift v2 as:


func dataForKey(key: String) throws -> [NSObject: AnyObject]


The Objective-C method Is also commonly paired with this shortened form:


- (nullable NSDictionary *) dataForKey: (NSString *) key;


This short method just calls the main one with a NULL for the NSError**. The signature for the short method is remarkably similar to the Swift throwing method. If I leave the short method in my Objective-C header, then errors ensue:


warning: no calls to throwing functions occur within 'try' expression
        do { let data = try self.account.dataForKey(kPrivateKey)
                       ^


Obviously, the compiler has chosen the wrong signature. If one comments out the short method, then the app compiles just fine. In code I control, this is obviously not that much of a problem. I comment out the short method and add NULLs to all the places it was called in my legacy code. The problem comes from commercial Frameworks I link against that adopt the short method pattern. There is no way to fix their code.


Or is there a workaround to the above problem? I have tried using the NS_SWIFT_NOTHROWS annotation. It allows me to retain my Swift v1.2 code without change.


I argue this is a compiler problem and should be fixed. In the meantime, I will raise an issue against the commercial frameworks I use. I assume folks would like a radar to the above effect?

Answered by OOPer in 47615022

My Xcode7 beta 6 suggested this signature:

let data = try self.account.dataForKey(kPrivateKey, error: ())

This may not be what you expect, but it seems both dataForKey methods are available in Swift.

Accepted Answer

My Xcode7 beta 6 suggested this signature:

let data = try self.account.dataForKey(kPrivateKey, error: ())

This may not be what you expect, but it seems both dataForKey methods are available in Swift.

WoW! What an odd construct. It appears to work. Thank you for taking the time to look into my issue.

Swift v2 Error Handling: Shadowing the method that throws...
 
 
Q