· 1 min learn
On this fast tutorial I am going to present you the right way to get all of the doable values for a Swift enum kind with a generic resolution written in Swift.
From Swift 4.2 you’ll be able to merely conform to the CaseIterable
protocol, and also you’ll get the allCases
static property totally free. In case you are studying this weblog put up in 2023, it’s best to positively improve your Swift language model to the most recent. 🎉
enum ABC: String, CaseIterable {
case a, b, c
}
print(ABC.allCases.map { $0.rawValue })
In case you are concentrating on beneath Swift 4.2, be at liberty to make use of the next technique.
The EnumCollection protocol strategy
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 write down an excessive amount of code in any respect.
public protocol EnumCollection: Hashable {
static func circumstances() -> AnySequence
static var allValues: [Self] { get }
}
public extension EnumCollection {
public static func circumstances() -> 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.circumstances())
}
}
Any longer you solely have to evolve your enum
varieties to the EnumCollection protocol and you may benefit from the model new circumstances technique and allValues
property which is able to include 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.circumstances() {
print(weekday.rawValue)
}
print(Weekdays.allValues.map { $0.rawValue.capitalized })
Observe that the bottom kind of the enumeration must be Hashable
, however that’s not an enormous deal. Nevertheless this resolution seems like previous tense, identical to Swift 4, please take into account upgrading your challenge to the most recent model of Swift. 👋
Associated posts
Study the whole lot about logical varieties and the Boolean algebra utilizing the Swift programming language and a few fundamental math.
Discover ways to talk with API endpoints utilizing the model new SwiftHttp library, together with async / await help.
The one and solely tutorial that you’re going to ever must study greater order capabilities like: map, flatMap, compactMap, cut back, filter and extra.
Study the very fundamentals about protocols, existentials, opaque varieties and the way they’re associated to generic programming in Swift.