Swift 2.0 interop with Objective C not working as expected?

I am migrating Swift 1.2 environment to 2.0. After fixing 3 million compiler errors accounted for by the new Swift 2.0 error handling scheme, I was finally able to link my test application (written in Objective C) to use the updated framework.

Xcode version 7.0 beta 3 (7A121l)

However, I got a problem. Some Swift functions are no longer generated into the auto-generated Objective C header (MyFramework-Swift.h) used by the Objective C test application.

Here is an example of a function not showing up: (My actual frame function was returning an enum, but I tried to simplify to illustrate the problem more clearly).

public func calculateImportantValueDangerously() throws -> Int  
{  
    return 42  
}  

      

Note that other functions like the ones below do appear to be expected (and can be called):

public func doSomething()  
{  
}  

public func doSomethingDangerous() throws  
{  
}  

public func calculateMeaninglessValue() -> Int  
{  
    return -1  
}  

      

Here's the Objective C side:

MyClass *newInstance = [[MyClass alloc] init];  
[newInstance doSomething];  

NSError *error = nil;  
[newInstance doSomethingDangerousAndReturnError:&error];  

long meaninglessValue = [newInstance calculateMeaninglessValue];  
NSLog(@"%ld", meaninglessValue);  

long importantValue = [newInstance calculateImportantValueDangerouslyAndReturnError:&error]; <-COMPILE ERROR
NSLog(@"%ld", importantValue);  

      

From watching this video, I expected it to "just work":

https://developer.apple.com/videos/wwdc/2015/?id=401

... but it looks like we cannot currently use functions that cast and return a value.

Is this a bug or is the function not implemented? We apologize if I missed anything in the release notes.

Any advice is appreciated.

+3


source to share


2 answers


It's impossible.

If you annotate your method with @objc

, you will see a problem.



The throw method cannot be marked as @objc because it returns a value of type 'Int'; return 'Void' or a type that connects to the Objective-C class

You can only return objects, primitives are not supported.

+2


source


Although the answer chosen is correct; you cannot return Int for a throwing function, I would like to point out an alternative solution as Apple has this same problem for a function in a CoreData structure:

func countForFetchRequest(request: NSFetchRequest, error: NSErrorPointer) -> Int

      



Note that in this case Apple does not use the throw pattern and instead falls back to the classic NSError out parameter mechanism.

+1


source







All Articles