优雅的方法来检查元组中的任何一个值是否为零

Woo*_*ock 6 tuples optional ios swift

我想知道是否有人有一个更优雅的方法来检查一个元组中的任何一个值在Swift中是否为Nil?

目前我正在检查这样:

    var credentials = CredentialHelper.getCredentials() //returns a tuple of two Optional Strings.

    if (credentials.username == nil || credentials.password == nil)
    {
        //continue doing work.
    }
Run Code Online (Sandbox Code Playgroud)

如果可能的话,我想要更简洁的东西.

Abi*_*ern 6

您可以使用元组值上的开关案例来完成此操作.例如:

func testTuple(input: (String?, String?)) -> String {
    switch input {
    case (_, .None), (.None, _):
        return "One or the other is nil"
    case (.Some(let a), _):
        return "a is \(a)"
    case (_, .Some(let b)):
        return "b is \(b)"
    }
}

testTuple((nil, "B"))  // "One or the other is nil"
testTuple(("A", nil))  // "One or the other is nil"
testTuple(("A", "B"))  // "a is A"
testTuple((nil, nil))  // "One or the other is nil"
Run Code Online (Sandbox Code Playgroud)

诀窍是对元组值使用let绑定.