Swift enum all values – The.Swift.Dev.


From Swift 4.2 you possibly can merely conform to the CaseIterable protocol, and you will get the allCases static property free of charge. If you’re studying this weblog submit in 2023, you need to undoubtedly 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 focusing on beneath 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 you do not have to jot down an excessive amount of code in any respect.

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

public extension EnumCollection {

    public static func instances() -> AnySequence<Self> {
        return AnySequence { () -> AnyIterator<Self> 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())
    }
}

To any extent further you solely have to adapt your enum sorts to the EnumCollection protocol and you’ll benefit from the model new instances methodology and allValues property which is able to comprise all of the doable 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 is not an enormous deal. Nonetheless this resolution seems like previous tense, identical to Swift 4, please take into account upgrading your challenge to the newest model of Swift. 👋

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles