1
3

More than 1 year has passed since last update.

【Swift】enumの値をランダムで返す

Posted at

はじめに

enumで定義した値をランダムで取得したい時の方法です。

実装

enum Sample: Int, CaseIterable {
    case one = 0
    case two = 1
    case three = 2
    
    static func random() -> Sample {
        Sample(rawValue: Int.random(in: 0...Sample.allCases.count)) ?? .one
    }
}

使い方

print(Sample.random())

おわり

enumをIntに準拠させて、Int.randomを使ってenumをランダムに取得します

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