【发布时间】:2014-06-20 10:04:10
【问题描述】:
我确定你去过那里。你想说“如果 flib 这样做,如果 flob 这样做,如果 flab 做饮食等等”,其中任何数量都可以是真的,那么最后你想要一个“如果你没有做任何一个”。
例如(下面的例子是用 Swift 编写的,因为我一直在使用它,但我认为大多数语言的情况都是一样的):
let thing = 101
var isInteresting = false
if (thing % 3 == 0) {
println("\"\(thing)\" is a multiple of three.")
isInteresting = true
}
if (thing > 100) {
println("\"\(thing)\" is greater than one hundred.")
isInteresting = true
}
if (thing > 1000) {
println("\"\(thing)\" is greater than one thousand.")
isInteresting = true
}
if !isInteresting {
println("\"\(thing)\" is boring.")
}
我发现跟踪一个布尔值来告诉我我是否做了任何事情有点笨拙。
我想出的唯一其他方法是:
let thing = 101
let isAMultipleOfThree = (thing % 3 == 0)
let isGreaterThan100 = (thing > 100)
let isGreaterThan1000 = (thing > 1000)
if isAMultipleOfThree {
println("\"\(thing)\" is a multiple of three.")
}
if isGreaterThan100 {
println("\"\(thing)\" is greater than one hundred.")
}
if isGreaterThan1000 {
println("\"\(thing)\" is greater than one thousand.")
}
if !(isAMultipleOfThree || isGreaterThan100 || isGreaterThan1000 ) {
println("\"\(thing)\" is boring.")
}
但如果有更糟糕的情况(如果你添加一个新子句,你需要记住在三个地方添加它。
所以我的问题是,有没有一种简洁明了的方法?
我梦想着一个虚构的类似 switch 的语句:
switchif { //Would have fallthrough where every case condition is checked
case thing % 3 == 0:
println("\"\(thing)\" is a multiple of three.")
case thing >100 :
println("\"\(thing)\" is greater than one hundred.")
case thing > 1000:
println("\"\(thing)\" is greater than one thousand.")
none: //Unlike 'default' this would only occur if none of the above did
println("\"\(thing)\" is boring.")
}
【问题讨论】:
-
您需要了解
else关键字。 -
我认为没有比你所做的更好的选择。
-
继续,Piokuc,演示“else”语句将如何提供帮助。
标签: if-statement switch-statement boolean-logic