Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Swift clases with overloaded methods in Objective C

Currently, my project uses both, Swift and Objectice-C languages. To get it to work, I’ve followed the guidelines from official documentation . And now I'm able to use Swift in Objective-C, and vice versa.

But the problem arises when some of the Swift clases have overloaded methods. Swift supports method overloading but not Objective-C.

Example:

func random(#lower: Int , upper: Int) -> Int {
    return lower + Int(arc4random_uniform(UInt32(upper - lower + 1)))
}

func random(#lower: CGFloat , upper: CGFloat) -> CGFloat {
    return CGFloat(arc4random() % 1) / 0
}

The auto generated file “MyNameProductModule-Swift.h” can’t compile because there are methods with the “same” signature.

Questions:

a) Am I missing something important?

b) Is there any solution other than rename the methods?

c) If I will create a Framework/Library with Swift, should i take care of not writing any overloaded method if this Framework/Library is designed to use it with Objective C too?

Thanks!

like image 915
Víctor Albertos Avatar asked Dec 14 '22 20:12

Víctor Albertos


2 Answers

As of swift2.0 you can differentiate if you're planning on using both in Objective C:

@objc(randomLoInt:HiInt:)
func random(#lower: Int , upper: Int) -> Int {
    return lower + Int(arc4random_uniform(UInt32(upper - lower + 1)))
}

@objc(randomLoFlt:HiFlt:)
func random(#lower: CGFloat , upper: CGFloat) -> CGFloat {
    return CGFloat(arc4random() % 1) / 0
}

or if you're not going to use this in your ObjC side of the project at all, just use:

@nonobjc
func random(#lower: Int , upper: Int) -> Int {
    return lower + Int(arc4random_uniform(UInt32(upper - lower + 1)))
}

@nonobjc
func random(#lower: CGFloat , upper: CGFloat) -> CGFloat {
    return CGFloat(arc4random() % 1) / 0
}
like image 67
Andrew Avatar answered Feb 24 '23 07:02

Andrew


a) Am I missing something important?

No you are not

b) Is there any solution other than rename the methods?

Unfortunately not. However, you can keep the methods implemented as you have them and add two different functions that call this that are only meant for exposing to Objective-C. That way, Swift code can still use the method overloaded version.

c) If I will create a Framework/Library with Swift, should i take care of not writing any overloaded method if this Framework/Library is designed to use it with Objective C too?

Yes, if you want to write a framework to be used by both Objective-C and Swift, you will need to make sure the API is fully compatible with Objective-C. There are a number of Swift features that are not compatible with Objective-C. You can still use these internally to your framework, but they cannot be made part of the API that you will expose to Objective-C.

like image 37
drewag Avatar answered Feb 24 '23 07:02

drewag