【问题标题】:How to call Swift function with more than one parameter from Objective C class?如何从 Objective C 类中调用具有多个参数的 Swift 函数?
【发布时间】:2014-09-17 09:39:29
【问题描述】:

例如我在swift中有这个方法:

@objc class MyClass: NSObject
....
@objc class func viewWithIndex(index: Int, str: String) {
    println(index, str)
}

然后我想在我的 Objective-c 类中调用该方法,我期待像这个调用 [MyClass viewWithIndex:10 str:@"string"]; 一样简单,但它不起作用。

我怎么称呼它?请帮忙。

注意:我已经对objective-c [MyClass showSomething]; 进行了有效的快速函数调用,这意味着我已经成功设置了必要的设置来桥接类。只有具有两个以上参数的函数是我的问题。 :)

已解决:

我不知道我发生了什么,但我刚刚重新启动了我的 mac 并删除了 objc,它与调用 [MyClass viewWithIndex:10 str:@"string"]; 一起工作。我记得在文档中阅读过。

Migrating Your Objective-C Code to Swift

  • 要在 Objective-C 中可访问和可用,Swift 类必须是 Objective-C 类的后代,或者必须标记为 @objc。

【问题讨论】:

  • 什么不起作用?你有编译时错误还是运行时错误?
  • 你的 Swift 类是 NSObject 的子类吗?比较stackoverflow.com/questions/25605677/…
  • 我已经对objective-c 类进行了有效的快速函数调用,但没有参数或只有一个参数。现在我想尝试两个或更多参数。它犯的错误是No Known class method for selector viewWithIndex:str
  • 你做了#import YOUR_PROJECT_NAME-Swift.h 吗?
  • 我已经导入并制作了桥头文件。

标签: ios objective-c xcode swift


【解决方案1】:

这在 Swift 3.0 中对我有用

public class func viewWithIndex(_ index: Int, str: String) {
    println(index, str)
}

在 Swift 声明的第一个参数之前添加下划线允许我从目标 c 调用而不命名第一个参数,如下所示:

[MyClass viewWithIndex:10 str:@"string"]

【讨论】:

  • 这确实节省了很多时间。谢谢
  • 方法参数列表开头的下划线实际上是做什么的? ..viewWithIndex(_ index..。我可以确认这也适用于我,但这里发生了什么?此令牌在此上下文中是否有名称?
  • @JamesTSnell _ 确定调用方法时是否应使用参数名称。在上面的示例中,即使从 swift 调用该方法也会看起来像这样:className.viewWithIndex(10, str: "test")。如果方法定义在 index 和 str 之前都有 _,那么方法调用将如下所示:className.viewWithIndex(10,"test")
  • 不能调用所有参数都命名的swift函数吗?
【解决方案2】:

我相信您需要将函数标记为公共(有意义)或动态。否则它将成为 Swift 优化(内联或 vtable 方法)的候选对象,这将使其对 Objective-C 不可见。

试试这个:

public class func viewWithIndex(index: Int, str: String) {
    println(index, str)
}

或者这个:(没有什么意义,但应该也可以)

private dynamic class func viewWithIndex(index: Int, str: String) {
    println(index, str)
}

【讨论】:

  • 我不知道发生了什么,但是当我今天早上打开我的 Mac 并删除 @objc 时,它在调用 [MyClass viewWithIndex:10 str:@"string"]; 时正常工作
  • OK,一定是方法已经在使用动态调度了。如果不是,我发现上述方法有效。 .应该适用与在 Swift 中使用 KVO 的指南相同的规则。
  • 我想我不需要publicdynamic 等,因为我的类子类是NSObject
  • 从 Xcode6 beta 6 开始,Swift 仍然可以在 NSObject 子类上内联/vtable 方法/变量。这绝对适用于私有变量(这是有道理的),但是如果您希望它是私有的,除了 Objective-C 运行时,您可以添加“动态”修饰符。
【解决方案3】:

在objective-c的.h文件中前向声明你的类

@class <MySwiftClass>

在 obj-c .m 类中导入“Productname-swift.h” 使用

[SwiftClass storeWithData:@"Hi" password:@"secret"];

SwiftClass.swift

@objcMembers class SwiftClass{
   public class func store(data: String,password:String)->Bool{
    let saveSuccessful: Bool = KeychainWrapper.standard.set(data, forKey: password)
    return saveSuccessful;
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-09-17
    • 2014-07-27
    • 2019-03-08
    • 2018-11-10
    • 1970-01-01
    • 2018-03-06
    • 1970-01-01
    • 2013-10-17
    相关资源
    最近更新 更多