3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Swift】条件分岐 if文 / switch文の基本

Posted at

概要

現在Swift学習中の筆者の備忘録です。
Swiftの条件分岐のif文とswitch文について基本をまとめます。

if文

if 条件A {
  // 条件Aに合致した時に実行する処理
} else if 条件B {
  // 条件Bに合致した時に実行する処理
} else {
  // 条件A・Bどちらにも合致しない時に実行する処理
}

サンプル


let score = 75
let result: String
// if文の中で使う定数はif文の外で定義する必要がある。

if score >= 80 {
  result = "優良"
} else if score >= 60 {
  result = "合格"
} else {
  result = "不合格"
}

print(result)
// 合格

switch文

switch  {
case ラベルA:
  // ラベルAに合致した時に実行する処理
case ラベルB,ラベルC:
  // ラベルBもしくはCに合致した時に実行する処理
  // ラベルは複数まとめて指定できる
default:
  // 合致するラベルがない場合の処理
}

サンプル

let num = 43

switch num {
case 0:
  print("zero")
case 1,2:
  print("1 or 2")
case 3...5:
  print("3 or 4 or 5")
  // 範囲演算子(...)を使ったパターン。この場合3から5の意。
case 6..<8:
  print("6 or 7")
  // 不等号を使った範囲演算子(..<)を使ったパターン。この場合6から7(8未満)の意。
case let n where n > 20:
  print("\(n) is more 20")
  // 新たな定数を定義して式(ここではnum)の結果を代入し、条件を指定する。
default:
  break
  // switch文を終了させる。
}

if文とswitch文の使い分け

同じ内容の条件式を書いて比べてみます。

例1)決まった範囲で処理を分ける

定数scoreが80以上だったら「A」、60以上だったら「B」、それ他は「C」と出力する

// if文
let score = 75

if score >= 80 {
  print("A")
} else if score >= 60 {
  print("B")
} else {
  print("C")
}
// B

// switch文
let score = 75

switch score {
case let s where s >= 80:
    print("A")
case let s where s >= 60:
    print("B")
default:
    print("C")
}
// B

これはif文の方が直感的に分かりやすい感じがします。
switch文ではcase内でscoreとは別に定数を定義する必要が出てきます
(先にInt型で定義されたscoreを、真偽を判定するBool型としては使えないため)。
これがif文の方が分かりやすい原因でしょう。

例2)限られた条件の中で処理を分ける

定数numが1なら「A」、 2なら「B」、他なら「C」とする場合

// if文
let num = 2

if num == 1 {
  print("A")
} else if num == 2 {
  print("B")
} else {
  print("C")
}
// B

// switch文
let num = 2

switch num {
case 1:
    print("A")
case 2:
    print("B")
default:
    print("C")
}
// B

この場合は、switch文の方が分かりやすそうです。
条件が3つぐらいと少なく、その中で処理を分けるような場合は
switch文の方が良さそうですね。

最後に

以上、簡単ですが条件分岐についてでした。

if文とswitch文の簡単な比較を行いましたが、
「if」の方がなんとなく親しみのある言葉なので、
初めのうちはこちらに頼りがちになりそうだなと思ったり。

switch文の方がすっきり記述できる場合もあるので、
意識的に使っていきたいです。

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?