LoginSignup
1
2

More than 3 years have passed since last update.

[Swift]enumでランダムなケースを返すextension

Posted at

実装


public protocol Sampling {
  static var all: [Self] { get }
  static var sample: Self? { get }
}

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

extension Sampling where Self: CaseIterable {
  static var all: [Self] { return self.allCases as! [Self] }
}

使い方

enum Basic {
  case one
  case two
}

enum IteratableBasic: CaseIterable {
  case one
  case two
}

enum Nums: Int {
  case zero
  case one
}

enum IteratableNums: Int, CaseIterable {
  case zero
  case one
}

enum Args {
  case str(String)
  case num(Int)
}

extension Basic: Sampling {
  static var all: [Basic] { return [.one, .two] }
}
extension IteratableBasic: Sampling {}
extension Nums: Sampling {
  static var all: [Nums] { return [.one, .zero] }
}
extension IteratableNums: Sampling {}
extension Args: Sampling {
  static var all: [Args] { return [.num(123), .str("mes")] }
}

Basic.sample
IteratableBasic.sample
Nums.sample
IteratableNums.sample
Args.sample

1
2
1

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