Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift "h" must be bound in every pattern error - Switch problems

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        
}
like image 621
user7024499 Avatar asked Dec 07 '16 23:12

user7024499


Video Answer


2 Answers

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")
}
like image 111
OOPer Avatar answered Sep 25 '22 10:09

OOPer


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()
like image 26
Display Name Avatar answered Sep 21 '22 10:09

Display Name