17.2 C
Canberra
Monday, October 27, 2025

Swift enum all values – The.Swift.Dev.



· 1 min learn


On this fast tutorial I am going to present you how one can get all of the attainable values for a Swift enum kind with a generic answer written in Swift.

From Swift 4.2 you possibly can merely conform to the CaseIterable protocol, and also you’ll get the allCases static property free of charge. If you’re studying this weblog submit in 2023, it’s best to positively improve your Swift language model to the newest. 🎉

enum ABC: String, CaseIterable {
    case a, b, c
}


print(ABC.allCases.map { $0.rawValue })

If you’re concentrating on under Swift 4.2, be at liberty to make use of the next methodology.

The EnumCollection protocol method

First we have to outline a brand new EnumCollection protocol, after which we’ll make a protocol extension on it, so that you don’t have to jot down an excessive amount of code in any respect.

public protocol EnumCollection: Hashable {
    static func instances() -> AnySequence
    static var allValues: [Self] { get }
}

public extension EnumCollection {

    public static func instances() -> AnySequence {
        return AnySequence { () -> AnyIterator in
            var uncooked = 0
            return AnyIterator {
                let present: Self = withUnsafePointer(to: &uncooked) { $0.withMemoryRebound(to: self, capability: 1) { $0.pointee } }
                guard present.hashValue == uncooked else {
                    return nil
                }
                uncooked += 1
                return present
            }
        }
    }

    public static var allValues: [Self] {
        return Array(self.instances())
    }
}

Any more you solely have to adapt your enum varieties to the EnumCollection protocol and you may benefit from the model new instances methodology and allValues property which can include all of the attainable values for that given enumeration.

enum Weekdays: String, EnumCollection {
    case sunday, monday, tuesday, wednesday, thursday, friday, saturday
}

for weekday in Weekdays.instances() {
    print(weekday.rawValue)
}

print(Weekdays.allValues.map { $0.rawValue.capitalized })

Word that the bottom kind of the enumeration must be Hashable, however that’s not a giant deal. Nevertheless this answer appears like previous tense, identical to Swift 4, please think about upgrading your undertaking to the newest model of Swift. 👋

Associated posts


· 6 min learn


Be taught every part about logical varieties and the Boolean algebra utilizing the Swift programming language and a few primary math.


· 4 min learn


Discover ways to talk with API endpoints utilizing the model new SwiftHttp library, together with async / await assist.


· 9 min learn


The one and solely tutorial that you will ever have to study greater order features like: map, flatMap, compactMap, cut back, filter and extra.


· 5 min learn


Be taught the very fundamentals about protocols, existentials, opaque varieties and the way they’re associated to generic programming in Swift.

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

[td_block_social_counter facebook="tagdiv" twitter="tagdivofficial" youtube="tagdiv" style="style8 td-social-boxed td-social-font-icons" tdc_css="eyJhbGwiOnsibWFyZ2luLWJvdHRvbSI6IjM4IiwiZGlzcGxheSI6IiJ9LCJwb3J0cmFpdCI6eyJtYXJnaW4tYm90dG9tIjoiMzAiLCJkaXNwbGF5IjoiIn0sInBvcnRyYWl0X21heF93aWR0aCI6MTAxOCwicG9ydHJhaXRfbWluX3dpZHRoIjo3Njh9" custom_title="Stay Connected" block_template_id="td_block_template_8" f_header_font_family="712" f_header_font_transform="uppercase" f_header_font_weight="500" f_header_font_size="17" border_color="#dd3333"]
- Advertisement -spot_img

Latest Articles