3
3

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]enumから適当に一個選ぶ

Posted at

protocol EnumRandomized {
  static var all: [Self] { get }
  static var random: Self? { get }
}

extension EnumRandomized {
  static var random: Self? {
    let all = self.all
    if all.isEmpty { return nil }
    let index = Int(arc4random_uniform(UInt32(all.count)))
    return all[index]
  }
}

enum Hoge {
  case a
  case b
  case c
}

extension Hoge: EnumRandomized {
  static var all: [Hoge] {
    return [a, b, c]
  }
}

Hoge.randomみたいな感じで使う

3
3
2

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
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?