Date
Dec. 22nd, 2024
 
2024年 11月 22日

Post: Swift: Generate values collection of Enum types

Swift: Generate values collection of Enum types

Published 12:08 Aug 10, 2017.

Created by @ezra. Categorized in #Programming, and tagged as #iOS.

Source format: Markdown

Table of Content

Have you ever done this before:

public enum SomeEnumType: Int {
    case a, b, c

    public var allValues: [SomeEnumType] {
        return [.a, .b, .c]
    }
}

It's very annoying when you have to enter the cases twice, so I stumbled around in the bits and bytes and created an extension usable like this:

let all = SomeEnumType.allValues
// [SomeEnumType.a, SomeEnumType.b, SomeEnumType.c]

Remarkable is that it's usable on any enum without associated values.

But, do NOTE that this does not work for enums that have no cases.

import Foundation

public protocol EnumCollection: Hashable {}

public extension EnumCollection {
    /// Sequence of all cases
    public static var allCases: AnySequence<Self> {
        typealias S = Self
        return AnySequence { () -> AnyIterator<S> in
            var raw = 0
            return AnyIterator {
                let current: Self = withUnsafePointer(to: &raw) {
                    $0.withMemoryRebound(to: S.self, capacity: 1) {
                        $0.pointee
                    }
                }
                guard current.hashValue == raw else {
                    return nil
                }
                raw += 1
                return current
            }
        }
    }
}

public extension EnumCollection {
    /// Array of all cases
    public static var allValues: [Self] {
        return Self.allCases.map({ (e) -> Self in
            return e
        })
    }

}

Want to do more?

public extension EnumCollection where Self: RawRepresentable {
    /// Array of all raw values
    public static var allRaws: [Self.RawValue] {
        return Self.allValues.map({ (e) -> Self.RawValue in
            return e.rawValue
        })
    }

    /// Dictionary of all cases and raw values
    public static var allContents: [[Self: Self.RawValue]] {
        return Self.allValues.map({ (e) -> [Self: Self.RawValue] in
            return [e: e.rawValue]
        })
    }
}

public extension Array where Element: RawRepresentable {
    /// Array of all raw values
    public var rawValues: [Element.RawValue] {
        return map({ (e) -> Element.RawValue in
            return e.rawValue
        })
    }
}

If you prefer CocoaPods:

pod 'EnumCollection'

Github Repo: https://github.com/Meniny/EnumCollection

Pinned Message
HOTODOGO
The Founder and CEO of Infeca Technology.
Developer, Designer, Blogger.
Big fan of Apple, Love of colour.
Feel free to contact me.
反曲点科技创始人和首席执行官。
开发、设计与写作皆为所长。
热爱苹果、钟情色彩。
随时恭候 垂询