Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elegant way to check if either value in a Tuple is nil

I would like to know if anyone has a more elegant way to check if either of the values in a Tuple are Nil in Swift?

Currently I'm checking like this:

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

    if (credentials.username == nil || credentials.password == nil)
    {
        //continue doing work.
    }

I would like something more succinct, if possible.

like image 659
Woodstock Avatar asked Apr 04 '15 07:04

Woodstock


1 Answers

You can do it with a switch case on the tuple values. For example:

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"

The trick is to use let bindings on the tuple values.

like image 83
Abizern Avatar answered Sep 25 '22 02:09

Abizern