-
Notifications
You must be signed in to change notification settings - Fork 6
Home
EnumKit is a library that gives you the ability to simply access an enum associated value, without having to use pattern matching. It also offers many utilities available to other swift types, like updatability of an associated value and transformations.
Associated value extraction is a long time waited feature in the swift programming language. While we are waiting for it to be built in the language, ergonomics of existing syntax to extract an associated value from an enum case aren't nice to read or write.
Having an enum
enum Foo {
case bar(String)
case baz(Int)
case bla
}
let enumCase: Foo
take as example pattern matching:
if case let .bar(value) = enumCase { ... }
while writing the left side of the statement there is no autocompletion, as there is no way for xCode to understand we are trying to match a pattern of Foo
until the right side of the =
sign is wrote.
Also there is the problem that pattern matching can be used only in guard and if statements and it doesn't really return a boolean value, so that things like negations are impossible.
if !(case .bar = enumCase) { ... } // does not compile
This use case can be addressed just by having an empty if having all your logic in the else (or returning in the if scope when applicable).
The other way we currently have to access an associated value is with a switch
switch enumCase {
case let .bar(value): ...
default: ...
}
In those cases where we are interested in just one case in our algorithm is somewhat upsetting to see a switch with only one case and a default.
Even more, negations with this pattern are equally bad to read
// all cases except bla
switch enumCase {
case .bar, .baz: ...
case .bla: return
}
That's where EnumKit comes useful.