了解Swift 2.2选择器语法-#selector() [英] Understanding Swift 2.2 Selector Syntax - #selector()

查看:149
本文介绍了了解Swift 2.2选择器语法-#selector()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将项目的语法切换到Swift 2.2(xCode可以帮助我自动完成);但是,我不理解新的#selector()语法.

I am switching over the syntax of my project toward Swift 2.2 (which xCode helps me do automatically); however, I do not understand the new #selector() syntax.

例如:

timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, 
             selector: #selector(MyVC.timerCalled(_:)), //new selector syntax!
             userInfo: nil, repeats: true)

具有选择器#selector(MyVC.timerCalled(_:))

_:代表什么?您可以将其他变量添加到此选择器吗?说,#MyVC.timerCalled(_:whateverVar).

What does the _: signify? Can you add other variables into this selector? Say, #MyVC.timerCalled(_:whateverVar).

对于这种语法的不同之处(与早期版本的Swift中基于字符串的实现相反)的一般信息,我们深表感谢.

General info on what is different in this syntax as opposed to the string based implementation from earlier versions of Swift are greatly appreciated.

推荐答案

括号中的位是一种用于标识所需选择器的参数列表的机制.

The bit in parenthesis is a mechanism for identifying the argument list for the selector that you want.

我建议您查看通用命名提案来自Swift Evolution.它涵盖了您具有许多功能的情况,这些功能仅因其参数标签不同而需要引用它们.该文档中的示例为:

I recommend you look at the Generalized Naming proposal from Swift Evolution. It covers cases where you have a number of functions that differ only by their parameter labels and need to refer to them. The example from that document is:

extension UIView {
  func insertSubview(view: UIView, at index: Int)
  func insertSubview(view: UIView, aboveSubview siblingSubview: UIView)
  func insertSubview(view: UIView, belowSubview siblingSubview: UIView)
}

如果要获取其中之一的函数值,结果将是不明确的:

If you wanted to get a function value for one of those the result is ambiguous:

let fn = someView.insertSubview // ambiguous: could be any of the three methods

已实现的解决方案是在没有任何类型信息的代码中添加参数标签,这些代码会生成要消除歧义的函数值:

The solution implemented is to add the argument labels, without any type information to the code that generates the function value to disambiguate which you want:

let fn = someView.insertSubview(_:at:)
let fn1 = someView.insertSubview(_:aboveSubview:)

看看标签是如何添加到括号中的?

See how the labels are added in the parens?

该建议在最直接适用于您的问题的建议中发挥了作用:

This proposal played a role in the one that most directly applies to your question:

引用方法的Objective-C选择器

在这种特殊情况下,您要引用的选择器是timerCalled:,它是一个没有标签的参数的函数.因此 (_:).下划线表示未指定标签和冒号.

In this particular case the selector you want to refer to is timerCalled: which is a function of one parameter that has no label. Hence (_:). The underscore means the label is not specified and the colon.

这篇关于了解Swift 2.2选择器语法-#selector()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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