如果声明的话,Swift可选

时间:2015-06-24 12:45:14

标签: switch-statement where optional swift-playground

前几天做了一个课程,其中一个服务员试了一下,结果出现了一个有趣的错误。

如何在打开值为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.

干杯

1 个答案:

答案 0 :(得分:1)

更新

根据您的评论提供更多背景信息。与可选项进行比较没有任何效果:

.b-infoblock{
   margin-top: 0 !important
   clear: both;
}

如果可选项为var d: Int? = 4 if d < 5 {} // true ,则它仍为真值:

nil

这是为什么?好的var d: Int? = nil if d < 5 {} // still true 值实际上是nil.None)(见下文),在这种情况下,if .None < 5肯定大于5

原始

这里的问题是.None是一个可选的Int(正如你所指出的)。如果你检查它,你会看到这个(图片供参考):

enter image description here

如果您查看可选定义,您会看到一个选项是一个包含两种类型(let anAgeNone)的枚举。因此,我们只需检查Some即可确保其具有值:

Some