The swift 3 method in objective-c does not work without a visible @interface for 'MySwiftClass' declares a selector 'addX: andY'

we are trying to reference the fast methods inside the objective-c implementation.

Swift 3 Class:

import Foundation @objc class MySwiftClass: NSObject { override init() { super.init() } func sayHello() -> Void { print("hello"); } func addX(x:Int, andY y:Int) -> Int { return x+y } } 

Objective-C implementation (Objective-cm):

 #import "ProductModuleName-Swift.h" MySwiftClass* getData = [[MySwiftClass alloc]init]; [getData sayHello] //works [getData addX:5 addY:5] //No visible @interface for 'MySwiftClass' declares selector 'addX:addY' 
+14
source share
3 answers

If you press the "ProductModuleName-Swift.h" on the Xcode source file editor, you can see how the Swift methods map to Objective-C.

In your case it will be

 @interface MySwiftClass : NSObject - (nonnull instancetype)init OBJC_DESIGNATED_INITIALIZER; - (void)sayHello; - (NSInteger)addXWithX:(NSInteger)x andY:(NSInteger)y; @end 

which is called

 MySwiftClass* getData = [[MySwiftClass alloc]init]; [getData sayHello]; NSInteger result = [getData addXWithX:5 andY:5]; 

Best Swift 3 Method Name May Be

 func add(x: Int, y:Int) -> Int 

because x already an argument (external) to the name of the first parameter. You can also add the @objc() attribute to @objc() Swift definition to control the Objective-C name. For example, when

 @objc(addX:andY:) func add(x: Int, y: Int) -> Int { return x+y } 

it will be called from Objective-C as

 NSInteger result = [getData addX:5 andY:5]; 
+26
source

Like ekscrypto in Swift 4 or later @objc all functions require @objc if you use less versiΓ³n than Swift 4, this is enoguh @objc in the class.

+9
source

In my case, I forgot to add:

 #import "MyProject-Swift.h" 

To obj file c.

0
source

Source: https://habr.com/ru/post/1013059/


All Articles