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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With