Doing a course the other day and one of the attendants tried something out and it came up with an interesting bug.
How can this provide an result when it is switching on a case with value nil?
func canDrink(age: Int?, country: String)->bool{
switch (age, country){
case (let anAge, _) where anAge < 5: //playground still says anAge is an optional
return false
default:
return true
}
}
canDrink(15,"UK") // Returns true
canDrink(4,"UK") // Returns false
canDrink(nil,"UK") // Also returns false not an error.
Cheers
Update
To provide a bit more context, per your comment. There is nothing invalid about comparing against an optional:
and if the optional is
nilit will still be a true value:Why is this? Well a
nilvalue is literally.None(if .None < 5) (see below) and in this case5is definitely greater than.None.Original
The problem here is that
let anAgeis an optional Int (as you pointed out). If you inspect it you will see this (image for reference):If you take a look at the optional definition you will see an option is an enum with two types (
NoneandSome). So we can just check againstSometo make sure it has a value: