Swift

[Swift]enumから適当に一個選ぶ

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みたいな感じで使う