【发布时间】:2018-11-11 21:39:59
【问题描述】:
这个问题类似于 Swift 4 custom argument labels - required? 但更具体。在研究从 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(p1: String? = nil),这将允许您在没有参数的情况下调用函数(并且该值将默认为nil)
标签: swift function arguments label