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!
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
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With