Swift: 如何访问“_”参数的值?

Swift: How to access value of "_" parameter?

我注意到这是 Swift 中的一个有效函数:

func test(_:String) {
    print("How do I access '_'?")
}

如何访问参数?

编辑 附加问题,是否有 valid/good 用例?

这就是所谓的通配符匹配模式,引入它只是为了不能使用参数,因为你根本不关心它。

来自documentation

A wildcard pattern matches and ignores any value and consists of an underscore (_). Use a wildcard pattern when you don’t care about the values being matched against.

如果您需要访问参数值,您必须使用正确的标识符。


关于您问题的更新部分。我不知道你为什么要这样做(只是一个疯狂的想法),但如果你想完全隐藏 public class 方法的参数名称但仍然能够在private sub-class,你可以这样做:

public class Foo {
    func test(_: String, _: Int) {
        print("[Ignored]")
    }
}

private class Bar: Foo {
    override func test(stringArgument: String, _ intArgument: Int) {
        print("\(stringArgument) \(intArgument)")
    }
}

任何使用您的库的外部人员都会在不知道 test 方法的参数名称的情况下使用抽象 Foo

使用_的意义在于你对使用参数不感兴趣。一个示例用法是这样

if let _ = someVariable as? String {
   //Do stuff here if someVariable is a string
   //But I'm not interested in accessing the unwrapped value, so I set the unwrapped variable name to _
}

如何访问参数?

你不知道。使用该语法,您明确表示您不想访问参数。

用例

假设您可以访问非常强大的异步 API,如下所示。

func theAnswerToLife(success:(answer: String) -> (), failure:(error: NSError) -> ())

yes, of course I am keeping the implementation secret

现在,如果函数 theAnswerToLife 确实找到了答案,它会调用 success 闭包,否则会调用 failure

你被迫通过两个 closure/functions 但你真的只对 answer 感兴趣,如果出现问题你不介意实际错误。

所以你可以定义

func tellEveryone(answer: String) {
    print("The answer to life is " + answer)
}

func badNews(_:NSError) {
    print("Something went wrong, we will try again tomorrow")
}

badNews 可以作为第二个参数传递给 theAnswerToLife,以后看代码的人会立即明白 badNews 不关心接收到的参数。

theAnswerToLife(tellEveryone, failure: badNews)