· 1 min learn
On this fast tutorial I am going to present you easy methods to get all of the potential 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 totally free. If you’re studying this weblog submit in 2023, it is 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 beneath Swift 4.2, be happy to make use of the next methodology.
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 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())
}
}
To any extent further you solely have to adapt your enum
varieties to the EnumCollection protocol and you’ll benefit from the model new instances methodology and allValues
property which can include all of the potential 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 })
Notice that the bottom kind of the enumeration must be Hashable
, however that’s not a giant deal. Nonetheless this answer appears like previous tense, similar to Swift 4, please contemplate upgrading your venture to the newest model of Swift. 👋
Associated posts
· 2 min learn
Making a Swift framework should not be exhausting. This tutorial will provide help to making a common framework for advanced tasks.
· 1 min learn
On this fast tutorial I am going to present you easy methods to get all of the potential values for a Swift enum kind with a generic answer written in Swift.
· 11 min learn
Study all the pieces about Swift modules, libraries, packages, closed supply frameworks, command line instruments and extra.
· 6 min learn
Have you ever ever heard about Swift language attributes? On this article I am attempting to collect all of the @ annotations and their meanings.