Date
Sep. 8th, 2024
 
2024年 8月 6日

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.
反曲点科技创始人和首席执行官。
程序猿、设计师、奇怪的博主。
苹果死忠、热爱色彩斑斓的世界。
如有意向请随时 与我联系