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入門🔰】enum(列挙型)の使い方を初心者向けに簡単に解説してみました!

Posted at

Swiftには「enum(列挙型)」という便利な仕組みがあります。これは、関連する値をグループ化して扱うことができる機能で、コードの見やすさや安全性を高めるためによく使われます。

enum(列挙型)とは?

enum(イーナム)とは、あらかじめ決められた選択肢の中から値を扱いたいときに使う型です。

たとえば、「天気」を表す場合はこんなふうに書けます:

enum Weather {
    case sunny
    case cloudy
    case rainy
}

これで Weather という型を定義でき、次のように使えます。

switch文と組み合わせて使う

Weather. は省略して .sunny のように書くことができます。

let today = Weather.cloudy

switch today {
case .sunny:
    print("今日は晴れです!")
case .cloudy:
    print("今日はくもりです。")
case .rainy:
    print("今日は雨です☔️")
}

rawValue(生の値)を使う

enumに「文字列」や「数値」などの値を持たせることもできます。これを rawValue といいます。

例:文字列を持たせる

enum Direction: String {
    case north = "北"
    case south = "南"
    case east = "東"
    case west = "西"
}

let dir = Direction.north
print(dir.rawValue) // "北"

例:整数を持たせる

enum Rank: Int {
    case first = 1
    case second
    case third
}
print(Rank.second.rawValue) // 2(自動的に +1 される)

associated value(関連値)

enumのケースごとに値を持たせることもできます。これを「関連値(Associated Value)」といいます。

enum Transport {
    case car(name: String)
    case bicycle
    case airplane(company: String, flightNumber: Int)
}

let travel = Transport.car(name: "Toyota")

値を取り出すには、switch文を使います:

switch travel {
case .car(let name):
    print("車の名前は \(name) です")
case .bicycle:
    print("自転車で移動します")
case .airplane(let company, let number):
    print("飛行機は \(company) の便、番号 \(number) です")
}

最後に

Swiftの enum は、ただの列挙だけでなく、値を持たせたり分岐処理と組み合わせたりでき便利な機能だと思います!

enum(列挙型)の使い方を初心者向けに簡単にまとめて解説してみました、ぜひ参考にしてみてください!🤌

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