GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing littlebitesofcocoa.com — #318: Codable Enums 📠 In Bites #316 and #317, we began looking at Swift's new First off, lets try a basic example. Here's an enum:
If we simply do this:
We'll get an error: Type 'SpaceshipKind' does not conform to protocol 'Decodable'. We can get around this by making our enum a "raw" value type like a
Nice. Since This is a fine solution for simple use cases, but things get a little (alright, a lot) more involved when one or more of our enum cases has associated values. Here's an example:
If we compile now, we get that same does not conform... error. Let's fix that by extending our enum. First, since we'll be taking on more of the encoding and decoding logic ourselves, we'll need our own Swift Error type to throw when things go wrong.
Then, we'll need to tell Swift the keys we'll be using to encode or decode our data. We'll use another enum for this, this one adopting the built-in
At this point we simply have to implement two more functions:
First we want to add the ability to decode a new Let's look at the implementation of decoding all at once for clarity:
First we pull all the values out of the decoder's container. Then we check for each of our two possible cases, configuring ourselves and returning if successful. Finally, if we didn't return successfully and reach the end, we Neat. Last but not least, lets implement encoding:
This time we grab the encoder's container up front, then simply switch on ourselves to see which value to encode. Now our associated value enum can be encoded and decoded all we want. Nice! Pro Tip: Writing all of this by hand can get extremely tedious for anything more than a few simple cases. Try something like Sourcery (Bites #292, #294, and #295) to generate this more boilerplate-ish That's all for now, have a question or idea for a Bite? Send it to [email protected]. |
| You are visitor 01402792 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |