Date
Jul. 14th, 2024
 
2024年 6月 9日

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
I'm looking for a SOFTWARE PROJECT DIRECTOR / SOFTWARE R&D DIRECTOR position in a fresh and dynamic company. I would like to gain the right experience and extend my skills while working in great teams and big projects.
Feel free to contact me.
For more information, please view online résumé or download PDF
本人正在寻求任职 软件项目经理 / 软件技术经理 岗位的机会, 希望加⼊某个新鲜⽽充满活⼒的公司。
如有意向请随时 与我联系
更多信息请 查阅在线简历下载 PDF