Help us understand the problem. What is going on with this article?

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

実装

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

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away