Reputation: 12549
I know it is possible to test an optional vs optionals as described in this question: Swift: testing against optional value in switch case
But what I want to do is test a non-optional value with optional case values:
switch nonOptionalView{
case optionalView1:
// Do something
case optionalView2:
// Do something else
}
Xcode returns an error "Value of Optional xxx not unwrapped" and If I add a "?" at the end of the case statement, I get "? pattern cannot match values of type 'UIView'"
Upvotes: 1
Views: 380
Reputation: 324
You could take a look at this solution https://stackoverflow.com/a/26941591/2485238
I find the code is more readable than the if/else solution.
In your case it would be
switch nonOptionalView {
case .Some(optionalView1):
// Do something
case .Some(optionalView2):
// Do something else
default:
// Handle default case
}
Upvotes: 0
Reputation: 878
Currently pattern matching optional values isn't supported in the Swift standard library. However, you could easily execute your logic using if
/else if
statements:
if nonOptionalView === optionalView1 {
// Do something
} else if nonOptionalView === optionalView2 {
// Do something else
}
If you'd really like to be able to pattern match optional values, you can use operator overloading. To overload the pattern matching operator ~=
, place the following code in your project:
public func ~=<T : Equatable>(a: T?, b: T?) -> Bool {
return a == b
}
Now you'll be able to pattern match optional values just fine:
switch nonOptionalView {
case optionalView1:
// Do something
case optionalView2:
// Do something else
default:
// Handle default case
}
Upvotes: 1