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

Viewed 709

I'm doing the following, but I'm getting the following warning:

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

enum Seat {
    case middle
    case window
    case aisle(Int)
}

let m : Seat = .middle
let w : Seat = .window
let a : Seat = .aisle(5)

let seats = [m,w,a]

for seat in seats {
    if case let .middle = seat {
        print("middle")
    }
    if case let .window = seat {
        print("window")
    }
    if case let Seat.aisle(row) = seat {
        print("able to let row be the associatedvalue of seat; its value is: \(row)")
    }
}
3 Answers

It's simple. In the three cases, only aisle has an associated value of type Int. Your .middle & .window cases don't have an associated value to extract ie there isn't a value to bind. Just knowing that that's the case is enough. To make the warning go away change:

if case let .middle = seat

to:

if case .middle = seat

same for your .window case

You can use switch

 switch seat {
    case .middle:
        print("middle")
    case .window:
        print("window")
    case let .aisle(row):
        print("able to let row be the associatedvalue of seat; its value is: \(row)")
}

In addition to the other 2 correct answers, if you make Seat Equatable, you can compare with == for the cases that don't have an associated value:

enum Seat: Equatable {
    case middle
    case window
    case aisle(Int)
}

let m : Seat = .middle
let w : Seat = .window
let a : Seat = .aisle(5)

let seats = [m,w,a]

for seat in seats {
    if seat == .middle {
        print("middle")
    }
    else if seat == .window {
        print("window")
    }
    else if case .aisle(let row) = seat {
        print("able to let row be the associatedvalue of seat; its value is: \(row)")
    }
}

Note: I have also rewritten the last case as if case .aisle(let row) = seat which I think makes the let binding clearer when there is only a single variable to bind.

Related