Is underscore ignored or invalidated in switch statement in Swift?

I have a switch statement in Swift:

switch tuple {
    case (let someObject, let current, nil):
        return true

    // Other cases...
}

      

The tuple is of type (SomeObject?, SomeObject, SomeObject?)

and I speak English: match the case where the first two elements are not zero but the third (optional) nil.

Xcode 7 tells me that since I didn't use bindings someObject

and current

, I have to replace it with an underscore. But if I were to replace the first element in the tuple with an underscore, would it not also match the cases where the first element is nil, because that _

means the compiler is ignoring the value? I have a separate case for situations where the first element is zero.

For the record, it looks like my code is still working as I expect, but I want to be sure and I can't find any documentation anywhere.

+3


source to share


1 answer


The underscore matches any value (nil or non-nil), but this is also the case for your template:

case (let someObject, let current, nil):

      

where the first let someObject

matches any value (nil or non-nil). So it doesn't really work the way you intended.

An optional type is defined as an enumeration:

enum Optional<T> : ... {
    case None
    case Some(T)
    // ....
}

      

and nil

matches Optional.None

. Therefore you can use



case (.Some, _, nil):
// Alternatively: 
case (.Some, _, .None):

      

to match the case where the first element is non-nil and the last element is zero. The middle item (SomeObject?, SomeObject, SomeObject?)

is not optional, so it cannot be zero.

In Swift 2 / Xcode 7, template x?

can be used synonymously for .Some(x)

, in your case

case (_?, _, nil):

      

matches the case when the first element is not nil and the last element is nil.

+10


source







All Articles