[ad_1]
From Swift 4.2 you possibly can merely conform to the CaseIterable protocol, and you will get the allCases static property totally free. If you’re studying this weblog publish in 2020, it is 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 })
If you’re focusing on under Swift 4.2, be at liberty to make use of the following 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 circumstances() -> AnySequence<Self>
static var allValues: [Self] { get }
}
public extension EnumCollection {
public static func circumstances() -> 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.circumstances())
}
}
Any more you solely have to evolve your enum sorts to the EnumCollection protocol and you’ll benefit from the model new circumstances methodology and allValues property which can 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 })
Be aware that the bottom sort of the enumeration must be Hashable, however that is not a giant deal. Nevertheless this answer appears like previous tense, identical to Swift 4, please contemplate upgrading your challenge to Swift 5. Thanks for studying, bye! 👋
[ad_2]
