What is the cause of this error in the switch statement "h must be bound in every pattern"?
I'm basically trying to use h as a variable for hour, make sure that it isn't nil (because hour is initially an optional value, and then see if it's greater than 17). I know I'm doing this wrong somewhere, but what is that pesky little 'h must be bound in every pattern' error?
let date = NSDate()
let calendar = Calendar.current
let components = calendar.dateComponents([.hour], from: date as Date)
let hour = components.hour
switch hour {
case let h, (h as Int) != nil, h >= 17:
return true
default:
return false
}
You may need to write something like this:
switch hour {
case let h? where h >= 17:
return true
default:
return false
}
Or, as suggested, using if
statement:
if let h = hour, h >= 17 {
return true
} else {
return false
}
Or else, simply:
return hour != nil && hour! >= 17
The error message is often found in this pattern:
enum MyEnum {
case patternA(Int)
case patternB(Int)
case patternC
}
let me = MyEnum.patternB(30)
switch me {
case .patternA(let h), .patternB(let h), .patternC: //<-
print("A or B with h, or C")
default:
print("this may never happen")
}
I tried this when I got the same error:
case .something, .other(let parameter) where parameter != nil:
doSomething()
I think, Swift 5 can't handle such complicated expressions, so I had to split it:
case .something:
doSomething()
case .other(let parameter) where parameter != nil:
doSomething()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With