简体   繁体   中英

Swift: Switch between two optional values

I'm trying to implement a switch between two option values:

import UIKit

var numOne: Int?
var numTwo: Int?

func doSomething() {
    switch (numOne, numTwo) {
    case (!nil, nil):
        print("something")
    case (_ == _):
        print("equal")
    default:
        break
    }
}

doSomething()

But I'm getting this errors:

In the first case I'm getting this error:

'nil' is not compatible with expected argument type 'Bool'

in the second case I'm getting this other error:

Expression pattern of type 'Bool' cannot match values of type '(Int?, Int?)'

My question for you guys is how can I manage to generate the cases between this to optional values?

I'll really appreciate your help

There's nothing wrong here; the syntax is just incorrect.

For the first case you mean:

case (.some, .none):

There's no such things as !nil . Optionals are not Booleans. You could also write (.some, nil) since nil is an alias for .none , but that feels confusing.

For the second case you mean:

case _ where numOne == numTwo:

The point here is you mean all cases ( _ ) where a condition is true ( where... ).


func doSomething() {
    switch (numOne, numTwo) {
    case (.some, .none):
        print("something")
    case _ where numOne == numTwo:
        print("equal")
    default:
        break
    }
}

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