How do I unwrap an Optional when pattern matching tuples in Swift?
You can use the x?
pattern:
case (1990...2015, let unwrappedUrl?):
print("Current year is \(year), go to: \(unwrappedUrl)")
x?
is just a shortcut for .some(x)
, so this is equivalent to
case (1990...2015, let .some(unwrappedUrl)):
print("Current year is \(year), go to: \(unwrappedUrl)")
with a switch case you can unwrap (when needed) and also evaluate the unwrapped values (by using where) in the same case.
Like this:
let a: Bool? = nil
let b: Bool? = true
switch (a, b) {
case let (unwrappedA?, unwrappedB?) where unwrappedA || unwrappedB:
print ("A and B are not nil, either A or B is true")
case let (unwrappedA?, nil) where unwrappedA:
print ("A is True, B is nil")
case let (nil, unwrappedB?) where unwrappedB:
print ("A is nil, B is True")
default:
print("default case")
}