这个问题类似于Swift 4自定义参数标签-是否必需?但更具体。在研究由var(不需要参数)更改为func(需要参数)而导致的问题时,我遇到了这个问题,但是却错过了更改所有引用的麻烦。我创建了一个游乐场,该游乐场与对该问题的后续编辑中的主张相矛盾:“问题不正确,因为自定义标签是强制性的”。我的问题是:如何正确表达我观察到的内容,如下所示:
class SomeTest {
static func someParam(p1: String?) -> String? {
return "hello \(p1 ?? "nothing")"
}
// Uncommenting the following causes error at let funny
// static func someParam(p2: String?) -> String? {
// return "hello \(p2 ?? "nothing")"
// }
static func doIt() {
let funny = someParam // ignoring the argument label is ok if there is no ambiguity
funny("thing") // and can be used without
someParam(p1: "thing2") // must have argument label
}
}
SomeTest.doIt()
如果您同时具有这两个someParam
函数(每个函数都有一个不同名称的参数),则该行:
let funny = someParam
不再起作用,因为不知道someParam
您指的是两个功能中的哪个。通过提供明确的名称可以解决此问题:
let funny = someParam(p1:) // or someParam(p2:)
请注意,funny
其类型为(String?) -> String?
。这两个someParam
函数具有相同的类型。这就是为什么您需要提供更多细节来消除两者的歧义。参数名称不会更改函数类型。
直接调用函数时,必须提供完整的函数名称,其中包括任何命名的参数标签。
但是,当您创建一个闭包变量并为其分配函数值时,如果该名字在给定的上下文中是明确的,则无需提供太多功能。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句