简体   繁体   中英

Switch testing a non optional against optional case values

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'"

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
}

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM