Skip to content

Instantly share code, notes, and snippets.

@bright23
Created February 15, 2017 09:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bright23/d980844fcf6d41144f16df7f07922a86 to your computer and use it in GitHub Desktop.
Save bright23/d980844fcf6d41144f16df7f07922a86 to your computer and use it in GitHub Desktop.
//
// EnumEnumerable+count.swift
// AdBlockSample
//
// Created by bright on 2016/11/08.
// Copyright © 2016年 bright. All rights reserved.
//
import Foundation
public protocol EnumEnumerable {
associatedtype Case = Self
}
public 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
}
}
public static func enumerate() -> EnumeratedSequence<AnySequence<Case>> {
return AnySequence(self.iterator).enumerated()
}
public static var cases: [Case] {
return Array(self.iterator)
}
public static var count: Int {
return self.cases.count
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment