-
Notifications
You must be signed in to change notification settings - Fork 0
Enumを配列で扱う
stv-ekushida edited this page Mar 9, 2018
·
1 revision
import Foundation
/// Enumの要素を配列で返せるようにするプロトコル
///
/// 参考 : https://qiita.com/sgr-ksmt/items/c1c6a91324cf12151256
/// countプロパティ、enumerateメソッドは、cases.count、cases.enumerated()で代用できるので採用しない。
internal protocol EnumEnumerable {
associatedtype Case = Self
}
internal extension EnumEnumerable where Case: Hashable {
private static var iterator: AnyIterator<Case> {
var n = 0
return AnyIterator {
defer { n += 1 }
let next = withUnsafePointer(to: &n) {
UnsafeRawPointer($0).assumingMemoryBound(to: Case.self).pointee
}
return next.hashValue == n ? next : nil
}
}
/// 要素を配列で返す
static var cases: [Case] {
return Array(self.iterator)
}
}