Swift optional unwrap string tuple

I have a function which returns a string tuple with optional values (String?,String?).

Trying to handle this with the help of switch case .

func getResult() -> (String?,String?) {
  return (nil,nil)// Could be John,nil or John,Edward
}

What I am interested is to handle two case where if first value is value is available use a specific case else if both values are available use another case, for other iteration's skip to default?

Also can we unwrap the string optional value in the switch case?

var names = getResult()
switch names {
case  let (firstName,lastName):
// This should execute only if both firstName and last name is not empty
// Also values should be unwrapped.
         print("Has both Names \(firstName) and \(lastName)") 
case let(firstName,nil):
// This should execute only if firstName is not empty. Also first name should be unwrapped value
         print("Has only first name \(firstName) ") 
default:
         break;
}

This would work as you wanted.

var names = getResult()
switch names {
case  let (firstName?, lastName?):
// This should execute only if both firstName and last name is not empty
// Also values should be unwrapped.
         print("Has both Names \(firstName) and \(lastName)") 
case let(firstName?, nil):
// This should execute only if firstName is not empty. Also first name should be unwrapped value
         print("Has only first name \(firstName) ") 
default:
         break;
}
1 Like
Terms of Service

Privacy Policy

Cookie Policy