Reputation: 3926
Swift 4.2 has an amazing piece of code to enumarate enums, and this question is not just about looping enums.
I had an enum like this:
enum MyEnum: String {
case session1 = "Morning"
case session2 = "Noon"
case session3 = "Evening"
case session4 = "Night"
}
Additionally, I want to return some object (Say sessionDetails). So I created an extension to it.
extension RawRepresentable where RawValue == String {
var details: <Some_Object_Type> {
/// Create & return corresponding object
}
}
So, If I want to get the noon session details, I can do like this:
MyEnum.session2.details
Alright! Now I want to group my sessions like first and second batch, etc. So there is a small addition of code in Enum:
enum MyEnum: String {
case session1 = "Morning"
case session2 = "Noon"
case session3 = "Evening"
case session4 = "Night"
static let firstBatch = [session1.details, session2.details]
static let secondBatch = [session3.details, session4.details]
static let weekendBatch = [session1.details, session4.details]
}
Note that, we can not use stored properties with enums. This is the need of "static" keyword here.
What I want:
I want to get batch items details. The below line will work:
MyEnum.firstBatch
It will give the session 1 & 2's details (objects).
Problem:
The above statement will run only once since it is a static. The details of each session is a dynamic one, and I want "details" should be called each time when I use the word .details
Note:
I have to give the grouped items details to some other util method. There is no way to change the util methods input structure. It just needs an array of objects to validate.
Help needed!!
Upvotes: 2
Views: 4338
Reputation: 54755
You just need to make the static properties computed instead of stored properties.
enum MyEnum: String {
case session1 = "Morning"
case session2 = "Noon"
case session3 = "Evening"
case session4 = "Night"
static var firstBatch:[String] {
return [session1.details, session2.details]
}
static var secondBatch:[String] {
return [session3.details, session4.details]
}
static var weekendBatch:[String] {
return [session1.details, session4.details]
}
}
Upvotes: 6