【问题标题】:How do I declare, create, and use method pointers in Swift?如何在 Swift 中声明、创建和使用方法指针?
【发布时间】:2016-03-16 02:09:53
【问题描述】:

我说的不是指向 C 函数的指针,而是指向 Swift 类型中的方法的指针。

struct Test: GeneratorType {
    var methodPointer: mutating () -> Bool?  // Non-working guess
    var which: Bool

    init() {
        which = false
        methodPointer = which ? &testMethod1 : &testMethod2  // Also non-working guess
    }

    //...
}

编译器说“mutating”作为函数声明的一部分是不合法的。 (实际上,它只是建议一个分号。)对于指针初始化(在我删除mutating 之后),编译器认为我正在尝试调用函数并使用它们的结果。我想在这里将这些方法用作对象本身,而不是作为函数调用。稍后我想在next 中使用指向方法;在没有弄清楚这一点的情况下,我将不得不求助于枚举标志并手动选择要在 next 中调用的方法。

我希望闭包机制的某些部分允许这样做。也许像this page, which describes functions returning functions 这样的东西。但我见过的例子都没有提到mutating 方法。

【问题讨论】:

  • 您提供的链接来自 2014 年 7 月,不应被信任。那是斯威夫特问世一个月后,那些文章往往具有误导性、不正确和过时。你可以尝试关于闭包的 Swift 文档。 developer.apple.com/library/prerelease/ios/documentation/Swift/…
  • 从查看this Tweet 来看,我认为mutating 方法不受支持,即使我能弄清楚如何调用非static 方法。
  • 我的尝试经常以“不允许部分应用'mutating'方法”结束。

标签: swift closures member-function-pointers


【解决方案1】:

看看这对你有没有帮助。

class Something {
    var f: ( () -> Int )?
    let f1 = { () -> Int in /* do some action here */ return 1}
    let f2 = { () -> Int in /* do some action here */ return 2}

    func ff(which: Bool) {
        f = which ? f1 : f2
    }

    func act() {
        if let f = f {
            f()
        }
    }
}

【讨论】:

  • 我试过了。它可以工作,但我可以访问selff1f2 的任何属性,所以它对我没用。
【解决方案2】:

这是我的做法 -

class FcnArgs {                             //@goal  pass a fcn as arg

    class func demo() {
        let fPtr = funcToPointTo;           //@type  '((Int)->String)'
        print(fPtr(4));
    }

    class func funcToPointTo(_ i : Int) -> String {
        print("I Was passed \(i)"); 
        return "I was returned";
    }
}

FcnArgs.demo() 输出:

I Was passed 4
I was returned

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-02
    • 2021-06-15
    • 2018-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多