【问题标题】:Inline Block/Function with Selector in SwiftSwift 中带有选择器的内联块/函数
【发布时间】:2015-01-18 20:25:52
【问题描述】:

Swift 中的内联选择器是否有本地语言功能?如果没有,是否有一个优雅的模式?

例如,使用 Selector 的 NSTimer。这是一种无需任何内联函数或块即可完成的方法:

var timer = NSTimer.scheduledTimerWithTimeInterval(2, target: self, selector: "update", userInfo: nil, repeats: false)

@objc func update() {
    print("timer up")
}

我宁愿有这样的东西。 这是一个概念,无法编译。

var timer = NSTimer.scheduledTimerWithTimeInterval(2,
        target: self,
        selector: { println("timer up") }, // What can I do here?
        userInfo: nil,
        repeats: false)

这类似于 question 询问有关 Objective C 中的内联选择器的问题。

【问题讨论】:

    标签: swift


    【解决方案1】:

    这段代码桥接到了 Objective-C,在那里没有办法做到这一点。您传递的字符串最终会转换为选择器 (SEL) 并传递给 objc_msgSend。所以,没有。

    您可以查看BlocksKit,其中adds these NSTimer methods 将在Swift 中转换为闭包。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-03
      相关资源
      最近更新 更多