LoginSignup
0
1

More than 5 years have passed since last update.

[Swift] CaseIterableなEnumの次の要素を取得する

Last updated at Posted at 2019-03-16

動機

N-State toggle buttonが欲しかった。

経緯

N個の状態を渡すと、ボタンを押すたびに順に状態が変わるボタン。
例えば ["State1", "State2", "State3", "State4"]を渡すと、クリックするたびにそのラベルが State1 → State2 → State3 → State4 → State1 → と変わっていくボタン。

Swiftなのだから、状態はenumで持ちたい。

そうなると、ローテーションができないのでは????

CaseIterableを使えばいけるかも。

結果

できた!

extension CaseIterable where Self: Equatable {

    func next() -> Self {

      let all = Array(Self.allCases)
      let count = all.count

      return all.firstIndex(of: self).map { all[($0 + 1) % count] }!
    }
}

問題点

あれ?
CaseIterable#allCasesの順番がどうなるかが不定...

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