1
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 1 year has passed since last update.

【Swift】switch文の使い方

Posted at

switch文とは

指定した変数や式の値に応じて、複数の分岐を取る処理を行うための構文です。

例文

let num = 3

switch num {
case 1:
    print("1が入力されました")
case 2:
    print("2が入力されました")
case 3:
    print("3が入力されました")
default:
    print("1〜3以外が入力されました")
}

変数「num」の値に応じて、それぞれの分岐に対応した処理が実行されます。もし「num」が3であれば、「3が入力されました」という文言が出力されます。

enumやタプルなどもswitch文の条件として利用することができます。

switch 100 - 99 {
case 1:
    print("1が入力されました")
case 2:
    print("2が入力されました")
case 3:
    print("3が入力されました")
default:
    print("1〜3以外が入力されました")
}

このように条件式を直接switch文の中に書くこともできます。

最後に

iOSアプリ開発をしています。
主にSwiftですが、最近は熱が入ってきてFlutterも🦾
色々やってます。もし良かったら見てってください。

1
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
1
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?