Swift 什么时候需要参数标签? [英] When are argument labels required in Swift?
问题描述
在回答这个问题时,关于调用<代码>初始化代码>.这在 Swift 中很正常.
In answering this question it came about that argument labels were required for a call to init
. This is normal in Swift.
class Foo {
init(one: Int, two: String) { }
}
let foo = Foo(42, "Hello world") // Missing argument labels 'one:two:' in call
然而,陌生人的力量正在发挥作用:
However, stranger forces are at play:
extension Foo {
func run(one: String, two: [Int]) { }
}
foo.run(one: "Goodbye", two: []) // Extraneous argument label 'one:' in call
要在此处使用参数标签,必须明确声明.
To use an argument label here it would have to be declared explicitly.
我还没有在文档中看到对所有这些进行非常彻底的解释.哪些类/实例/全局函数需要参数标签?Obj-C 方法是否总是使用参数标签导出和导入?
I haven't seen something very thorough explaining all of this in the documentation. For which varieties of class/instance/global functions are argument labels required? Are Obj-C methods always exported and imported with argument labels?
推荐答案
从 Swift 3.0 开始,这又发生了变化:所有方法、函数和初始值设定项都需要 所有 参数的参数标签,除非您有使用外部名称 _
明确选择退出.这意味着诸如 addChildViewController(_:)
之类的方法现在是这样编写的:
As of Swift 3.0 this has changed again: all methods, functions, and initializers require argument labels for all parameters, unless you have explicitly opted out using the external name _
. This means methods such as addChildViewController(_:)
are now written like this:
func addChildViewController(_ childController: UIViewController)
这是提议和批准的一部分Swift Evolution 流程,并在 SR-961.
This was proposed and approved as part of the Swift Evolution process, and was implemented in SR-961.
这篇关于Swift 什么时候需要参数标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!