Swift [条件分岐]
条件分岐
if
括弧は使っても問題ないが使わない方を推奨
if 条件式 {
処理
}
let age = 22 var shouldNotDrinkBeer = false if age < 20 { shouldNotDrinkBeer = false } else if age > 60 { shouldNotDrinkBeer = true } else { shouldNotDrinkBeer = false }
三項演算子
ある条件の評価後が true
であれば値Aを, false
であれば値Bを代入
let 変数 = 条件 ? 値A : 値B
let policemanMessage = hasDrivingLicense ? "OK. No Problem." : "I'll arrest you."
switch-case
Enumとの相性がいい
書かなくても break
が入っている状態
どの case
にも合致しない場合 default
の処理が実行される
意図的にフォールスルーしたい場合は fallthrough
を入れる
switch 変数 { case 条件: 処理 case 条件: 処理 case 条件: 処理 default: 処理 }
switch type { case .Normal: // Normal case .Special, .Temporary: // Special or Temporary default: // else }
比較も可能
var n = 10 switch n { case n < 10: // Do something case n < 20: // Do something default: break // No action }
他にもタプルや範囲指定も let where
も使えるがここでは割愛