【问题标题】:Cast ObjectiveC int and swift Int (Call Swift method from Objective-c with variables)Cast ObjectiveC int 和 swift Int(使用变量从 Objective-c 调用 Swift 方法)
【发布时间】:2017-05-21 04:55:00
【问题描述】:

我正在从 ObjectiveC 调用 Swift 函数

这些是我的简单代码

在我的目标 C 代码中

// mySwift class is put in delegate
[delegate testFunc]; // works well
int now = 10;
[delegate showCount:now]; //compile error

在我的快速代码中

class mySwift {
    func showCount(nowpos: Int){
       // my code
    }
    func testFunc(){
       // it works well
    }

我无法用这条消息编译它。

myObjC.m:171:19: No known instance method for selector 'showCount:'

如果我不使用变量(Make testfunction without variable),它工作得很好。

我猜是因为 Type (Int, and int)

我该如何解决这个问题??

【问题讨论】:

    标签: objective-c swift


    【解决方案1】:

    你说得对

    如果我不使用变量(使测试函数没有变量),它可以工作 好吧。

    但是让我们来了解一下为什么?

    在 Swift 中,函数参数有两个部分,即 labelparameter

     func showCount(nowPostion nowpos: Int) {}
    

    在上述函数中,标签是nowPositionnowposparamater。这种区别的用途是 label 由函数调用者使用,而 parameter 在函数内部使用。

         showCount(nowPostion: 50) // calling function using label
    

    但如果我不提供label,那么parameter 将被视为label,因此当您从Objective-C 调用该函数时,它无法找到此方法。

        [delegate showCount:now];
    

    此外,在 Objective-C 中,无法在方法调用中提供 parameter 名称。因此,我们必须在 Swift 定义中使用 _ 来调整它。

       func showCount(_ nowpos: Int)
    

    上面的定义说调用这个函数时不需要label

       func showCount(50) // This will work now
    

    在使用 Objective-C 和 Swift 互操作时有一些注意事项。

    【讨论】:

    • 感谢您的详细解释!!!!如果我添加“_”,我可以使用 Objective-c 之类的变量
    • 是的。 _ 将不再需要在从 Objective C 调用 swift 函数时添加参数名称。
    【解决方案2】:

    不要使用 _ 命名 swift 方法的第一个参数 func showCount(nowpos: Int)

    这样

    class SwiftClass:NSObject {
        public func showCount(_ nowpos: Int){
            // my code
        }
        func testFunc(){
            // it works well
        }
    }
    

    【讨论】:

      【解决方案3】:

      你应该这样写

      class mySwift {
         class func showCount(nowpos: Int){
             // my code
          }
      
      // calling
      myswift.showcount(nowpos:5)
      

      错误是因为你使用的方法没有创建类的实例,我写的例子是类方法,我们不需要实例来调用类方法

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-03-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-07-05
        • 2014-08-03
        • 1970-01-01
        相关资源
        最近更新 更多