Because it becomes too long, I extract only summary here.
You can read this idea in detail in github.com/ensan-hcl/Swift-GenericCase-Introduction/blob/master/Generic-case.md
Hi all! This is my first post. I hope you like it.
With today's Swift, dealing with enums with associated values in switch statements is very frustrating because we frequently face situations where we have to repeat common codes or write extra codes.
I suggest 'generic-case' to refine the syntax involving switch statements and enums with associated values. Generic-case greatly improves our way to deal with such situations. This works like this.
enum Either<First, Second>: CustomStringConvertible {
case first(First)
case second(Second)
}
switch either{
//declare generic type parameter `T` after `case` and cast value as `T`
case <T> let .first(value as T), let .second(value as T):
genericFunc(value) //call genericFunc<T>
}
This code works as if the patterns are separated from each other.
//translated to:
switch either{
case let .first(value):
genericFunc(value) //call genericFunc<First>
case let .second(value):
genericFunc(value) //call genericFunc<Second>
}
You can use type constraints, so that you can write codes like this.
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
switch self{
case <T: Encodable>
let .int(value as T),
let .string(value as T):
try container.encode(value, forKey: .value)
}
}
Because this is now only an idea, points that are maybe controversial and alternatives that I didn't select are all written in here. Here I wrote about its detailed design, limitations, and relating ideas for example Nested switch statements, Binding omission, and so on to make more use of generic-case.
What do you think about this generic-case and its relating ideas?