Home > Software design >  Swift enum - switch statement matching associated values warning
Swift enum - switch statement matching associated values warning

Time:04-30

I have an enum declaring associated values in Swift, along with a method that is trying to get a value at a specific location in that entry:

enum myEnum {

    case entry0(Float=0.0, Float=0.0)

    ...

}

var entry0XValue: Float {
    switch self {
    case .entry0(let x, let _):
        return x
    default:
        return 0
    }
}

The code works, but the problem I'm having here is when I compile this, the compiler is giving this warning:

'let' pattern has no effect; sub-pattern didn't bind any variables

This is referring to the underscore in the case switches. Is there any way to rewrite this to remove this warning?

CodePudding user response:

Spell it like

case .entry0(let x, _):

Or like

case let .entry0(x, _):

which works more generally like:

case let .entry0(x, y):

CodePudding user response:

The effect of a let <subpattern> pattern is that it binds values to identifier patterns that appear in <subpattern>, when the pattern is matched against. For example, the x in .entry0(let x, let _) is bound to 0.0, when you match it against MyEnum.entry0(0.0, 0.0) in a switch statement. Another example: when you do let (x, y) = (1, 2), the x and y are bound to 1 and 2 respectively. Note that in this case, <subpattern> is a tuple pattern, with identifier patterns inside it.

The let pattern let _ "has no effect" because there are no identifier patterns in <subpattern> (the wildcard pattern, _, in this case). As a result, the let pattern will match if and only if <subpattern> matches, which means that you don't need let at all. You can just write <subpattern> directly.

case .entry0(let x, _):

This removes the warning.

Since the .entry(...) part is also a pattern (an enumeration case pattern), you can write that part as the <subpattern>:

case let .entry0(x, _):

For more info on the syntax of patterns, see the Patterns section of the language reference.

  • Related