swift 3 method in objective-c fails with no visible @interface for 'MySwiftClass' declares the selector 'addX:andY'

前端 未结 3 1197
天涯浪人
天涯浪人 2020-12-08 14:35

we are trying to reference swift methods inside an objective-c implementation.

Swift 3 Class:

import Foundation
@objc class MySwiftClass: NSObject {         


        
3条回答
  •  攒了一身酷
    2020-12-08 15:10

    If you command-click on "ProductModuleName-Swift.h" in the Xcode source file editor then you can see how the Swift methods are mapped to Objective-C.

    In your case that would be

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

    which is called as

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

    A better Swift 3 method name might be

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

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

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

    it would be called from Objective-C as

    NSInteger result = [getData addX:5 andY:5];
    

提交回复
热议问题