LoginSignup
4
1

More than 5 years have passed since last update.

CaseIterableにindexプロパティを追加する

Posted at

CaseIterableを拡張し、indexプロパティを追加する実装です。

実装コード

extension CaseIterable where Self: Equatable {
    var index: Int {
        guard let index = Self.allCases.firstIndex(of: self) as? Int else { fatalError() }
        return index
    }
}

利用例

enum Season: CaseIterable {
    case spring
    case summer
    case fall
    case winter
}

let season: Season = .fall
print(season.index) // 2
4
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
4
1