Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
676 views
in Technique[技术] by (71.8m points)

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

we are trying to reference swift methods inside an 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-c.m):

#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'
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...