Search code examples
swiftswitch-statementoption-typeforced-unwrapping

How to handle optionals in switch statements


I've the following code:

for compareValues in [(optionalVal1, optionalVal2), (optionalVal3, optionalVal4)] {
    switch compareValues {
    case (nil, nil):
      break
    case (_, nil):
      return true
    case (nil, _):
      return false
    case let (lValue, rValue):
      return lValue < rValue
    }
}

This does not compile, the last line triggers this error:

Value of optional type 'String?' not unwrapped; did you mean to use '!' or '?'?

How would you suggest handling this without forced unwrapping lValue and rValue?


Solution

  • To unwrap the optionals in the case statement, you can use

    case let (.some(lValue), .some(rValue)):