0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

[Swift] switch文を簡単に解説!

Posted at

Swiftで条件分岐をする方法として有名なのがif文ですが、実はもう一つ便利な方法があります。それがswitch文です。

switch文とは

switch文は、ある値に対して複数のパターンを照らし合わせて処理を分けるための構文です。簡単にいうと、

「この値が○○だったらこれをする。△△だったら別のことをする」
というように、選択肢ごとに処理を分けることができます。

基本の書き方

let number = 2

switch number {
case 1:
    print("1です")
case 2:
    print("2です")
case 3:
    print("3です")
default:
    print("1〜3以外です")
}
  • switch の後に分岐したい値を書きます

  • case には判定したい値を書きます

  • default はどの case にも当てはまらなかったときの処理です

  • 各 case の中で break を書く必要はないです

範囲を使ったパターンマッチ

数値の範囲に応じて処理を変えたいときも、switchは便利です!

let score = 85

switch score {
case 90...100:
    print("素晴らしい!")
case 70..<90:
    print("よくできました")
case 50..<70:
    print("もう少しがんばろう")
default:
    print("再チャレンジが必要です")
}
  • 90...100 は 90〜100点までを含む範囲。

  • 70..<90 は 70以上90未満。

文字列にも使えます!

文字列の値に応じた処理もできます。

let fruit = "りんご"

switch fruit {
case "りんご":
    print("赤くておいしい")
case "みかん":
    print("冬にぴったり")
case "バナナ":
    print("エネルギー補給に最高")
default:
    print("知らない果物です")
}

まとめ

ポイント 説明
switch 値に応じた複数の分岐処理ができる
case 条件に一致する値を判定する部分
default どのcaseにも一致しないときの処理(必須)
break Swiftでは不要(自動で止まる)

if文では長くなりがちな条件分岐をスッキリ書けるので、ぜひ活用してみてください!
ぜひ参考にしてみてください!👍

0
0
1

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?