Skip to content

Instantly share code, notes, and snippets.

@Koze
Last active July 16, 2020 10:17
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Koze/59a1b31c45217b9f46c11737ba905534 to your computer and use it in GitHub Desktop.
Save Koze/59a1b31c45217b9f46c11737ba905534 to your computer and use it in GitHub Desktop.
index of CaseIterable enum
/*
Copyright (c) 2018 Kazume Koze
Released under the MIT license
https://opensource.org/licenses/mit-license.php
*/
//
// CaseIterable+Index.swift
//
//
// Created by Kazuma Koze on 2018/10/06.
// Copyright © 2018年 Climb App. All rights reserved.
//
import Foundation
extension Hashable where Self : CaseIterable {
var index: Self.AllCases.Index {
return type(of: self).allCases.firstIndex(of: self)!
}
}
enum Animal: Int {
case dog
case cat
case rabbit
}
let index: Int = Animal.cat.rawValue
enum Animal: Int, CaseIterable {
case dog = 1
case cat = 3
case rabbit = 4
}
let index: Int = Animal.allCases.firstIndex(of: .cat)!
enum Animal: String, CaseIterable {
case dog = "イヌ"
case cat = "ネコ"
case rabbit = "うさぎ"
}
let index: Int = Animal.allCases.firstIndex(of: .cat)!
enum Animal: CaseIterable {
case dog
case cat
case rabbit
}
let index: Int = Animal.allCases.firstIndex(of: .cat)!
enum Animal: CaseIterable {
case dog
case cat
case rabbit
}
let index: Int = Animal.cat.index
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment