Objective-C中的swift 3方法失败,"MySwiftClass"没有可见的@interface声明选择器"addX:andY" [英] swift 3 method in objective-c fails with no visible @interface for 'MySwiftClass' declares the selector 'addX:andY'

查看:105
本文介绍了Objective-C中的swift 3方法失败,"MySwiftClass"没有可见的@interface声明选择器"addX:andY"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在尝试在Objective-C实现中引用swift方法.

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

Swift 3类:

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实现(Objective-c.m):

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'

推荐答案

如果在Xcode中用命令单击"ProductModuleName-Swift.h" 源文件编辑器,然后您将看到Swift方法如何映射到Objective-C.

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.

在您的情况下

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

称为

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

更好的Swift 3方法名称可能是

A better Swift 3 method name might be

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

因为x已经是第一个的参数(外部)名称 范围.您还可以在Swift定义中添加@objc()属性 控制Objective-C名称.例如,使用

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
}

它将在Objective-C中称为

it would be called from Objective-C as

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

这篇关于Objective-C中的swift 3方法失败,"MySwiftClass"没有可见的@interface声明选择器"addX:andY"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆