私は Swift のステートメントに精通していますswitch
が、このコードを : に置き換える方法が知りたいですswitch
。
if someVar < 0 {
// do something
} else if someVar == 0 {
// do something else
} else if someVar > 0 {
// etc
}
ベストアンサー1
ここに 1 つのアプローチがあります。がまたは othersomeVar
であると仮定すると、オプションでオペランドを新しい変数に割り当てることができます。これにより、キーワードを使用して、任意のスコープを設定できます。Int
Comparable
where
var someVar = 3
switch someVar {
case let x where x < 0:
print("x is \(x)")
case let x where x == 0:
print("x is \(x)")
case let x where x > 0:
print("x is \(x)")
default:
print("this is impossible")
}
これは少し簡略化できます:
switch someVar {
case _ where someVar < 0:
print("someVar is \(someVar)")
case 0:
print("someVar is 0")
case _ where someVar > 0:
print("someVar is \(someVar)")
default:
print("this is impossible")
}
where
範囲マッチングを使用してキーワードを完全に回避することもできます。
switch someVar {
case Int.min..<0:
print("someVar is \(someVar)")
case 0:
print("someVar is 0")
default:
print("someVar is \(someVar)")
}