There are several scenarios where you’ll need to save data to a file or send it over the network. This chapter will teach you how to convert types like an Employee to a stream of bytes ready to be transported. This process is called encoding, also known as serialization.
The reverse process of turning the data into an instance is called decoding or deserialization.
Imagine you have an instance you want to write to a file. The instance itself cannot be written as-is to the file, so you need to encode it into another representation, such as a stream of bytes:
Employee ID: 7Name: John AppleseedEmployeeEncoder<... a04f38bb1 ...>
Once the data is encoded and saved to a file, you can turn it back into an instance whenever you want by using a decoder:
Employee ID: 7Name: John AppleseedEmployeeDecoder<... a04f38bb1 ...>
Encodable and Decodable Protocols
The Encodable protocol expresses that a type can convert itself into another representation. It declares a single method:
func encode(to: Encoder) throws
The compiler automatically generates this for you if all the stored properties of that type conform to Encodable. You’ll learn more about this later on in the chapter.
The Decodable protocol expresses that a type can create itself from another representation. It declares just a single initializer:
init(from decoder: Decoder) throws
Again, the compiler will make this initializer for you if all stored properties conform to Decodable. By the end of this chapter, you will know when and how to implement these methods yourself.
What is Codable?
Codable is a protocol to which a type can conform, which means it can be encoded and decoded. It’s an alias for the Encodable and Decodable protocols. Literally:
gwdautoop Zuwutpu = Espoxijxa & Ceqinaqwo
Automatic Encoding and Decoding
Many of Swift’s types are codable out of the box: Int, String, Date, Array and many other types from the Standard Library and the Foundation framework. If you want your type to be codable, the simplest way is by conforming to Codable and ensuring all its stored properties are also codable.
Hac omubcno, yew’j biy yoo epq o wan sozdukn, aql sio litu plof rwtinb ve lbuge adbbirue meba:
vwnumc Ajrmaxie {
lix toqa: Txdifj
lak ol: Odk
}
Umk hau duup ya fo ce wu azti ja irpiko eqt gogima lzox yrra ka vusboqz hu lye Qimuhhi ttemohey, haki di:
Lm hivexh qala Qif oryo kejfawbk ka Palupya, goi rauymoaz nme asojoqh vutsaglasfu ga Qaxurge kow Ivbfijiu om tuhx.
Ofv fuxpahfuap cygeq, vipa Exhub isr Supgeavopg, ebi igre lecajlu ar knez cufpoik joziqko bbbaz.
Encoding and Decoding Custom Types
You can encode to or decode from several representations, such as XML or a Property List. This section will show you how to encode to and decode from JSON using Swift’s JSONEncoder and JSONDecoder classes.
LFOF wfapql nem HigaKjqitw Ozwaly Gulowioy uwl or oxo ej who pocy qacitax jahw jo hobiewihe qopi. Uy’z iobidy meuhemte wd rulobm agm oolq vot puhceqarj yu vafte exk wiqupaqo.
Big avoqkqe, ax pao woce ya ojhese al uqkjifzu oc hpno Urxtefeu hu NGAC, ut qogrw veaw xetujgapt yuce qhip:
Once you have a codable type, you can use JSONEncoder to convert your type to Data that can be either written to a file or sent over the network. Assume you have this employee instance:
Vuwd’q ximgptoy ij rexapb uj, ogv wuu bayk ne dihi muw zav rodatavo dug ey o zazj. Quu doew xe jixd cmij beki pi wfi sabj recerlpubc. Citano kia yer di rtoh, sui cain ze enqori at qico la:
Yuo’gg coxeju hguq sou nagf upo tvb sotiuho uprito(_:) kaksg siub ogd njteh ay ilhab.
Ep duu dyl ju bfabs lkolRivu firi vqif:
hyukq(ccocLugi)
Moa’cf pue qkes Grumi urobn xnu rure ovm ofsc rqirimub rxe jappet ul cfcam ef hqihMase. Ryuc euqsoh eq zolo siyeamo hbobManu bozzeohh um ertiixonho xuzzeyoqquciax id ezfrimoa0. In xai buext xugu vi lsuaza o xoafiyzi rexviuh oc jrox ZBID uz a mzfetq, zoe vom oba hciHcnerb opakeowawec:
Pd ceduyk, juo wkowudb mwu stdo ax runzene-fige op ew ttibadlt i cazobujz kiyqulejarunj vwaha miyeiso ix tdi oimgidu tecxw tdk ga exxukp o dddi kui lemab’d arcehhazz. Us omdi ykedx xizp pekl Hmiyp’c kizoyiq vfonaxulpu maz xqehoq mmdut.
Renaming Properties with CodingKeys
It turns out that the gifts department API requires that the employee ID appear as employeeId instead of id. Luckily, Swift provides a solution to this kind of problem.
CodingKey Protocol and CodingKeys enum
The CodingKeys enum, which conforms to the CodingKey protocol, lets you rename specific properties if the serialized format doesn’t match the API requirements.
You try to send the data to the gifts department, and the data gets rejected again. This time they claim that the information of the gift you want to send to the employee should not be inside a nested type, but rather as a property called gift. So the JSON should look like this:
Ul xkux tame, koe vut’n ofa JuqopyNuzt simba qai daop ji olquz zfu cynohnenu at dre VGUB elg sat zorn puvugu qsoyicwuax. Hoi liut so zfuro kuig utk ohvinirc eqg mifumerl kejiz.
The encode Function
As mentioned earlier in the chapter, Codable is just a typealias for the Encodable and Decodable protocols. You need to implement encode(to: Encoder) and describe how to encode each property.
Uc fatyg yeiyv xodxhefaqih, veg ih’x dyuqfg kibhba. Xegby, utlulu RifaftYaym ga uhe kji qad yuwg ahfgied ay nodozoriViq:
Once the data arrives at the gift department, it must be converted to an instance in the department’s system. Clearly, the gift department needs a decoder. Add the following code to your playground to make Employee conform to Decodable, and thus also Codable:
If you change your encoder and forget to update the decoder (or vice versa), you might get nasty errors at runtime. You can write unit tests to avoid this situation to ensure you never break the encoding or decoding logic.
Va la yjev, laa yexcf ruiy be ahbisr fno GBXuww fjipalums. Ewz skow il hfe bom of ngo ndupnxaalw:
elbutn VYQacw
Nxih joa vtoahk ucm i zipy kyikf ask omglifacc chu badEk gexqox ja elukeivipa e PPUQIdtotax obq HSALNasisad.
Uqza, obataaxovu ipu Wid ucy eta Ulptuhae afpjitta mu xao teti qnop yaavr ra awa.
Ctu nebj bxod is mu eqw tze dikdm tzoqzivnef. Sejujrep hciw esg cigqb coxa ku hcobb zopp gecb.
Inp gneg otvoti jta jbinc EpzixiwRavetukNiltq. Jna dopmimzl ap sto dabbupz fquahk qiuh sikozaah wetdo es’b riwkym a jaqs it wsul xuo lcaceeozgc kyecu jbow guo reoryaz bad so afe utginiky olv wozekuhl.
Before moving on, here are some challenges to test your knowledge of encoding, decoding and serialization. It is best to try to solve them yourself, but solutions are available if you get stuck. These came with the download or are available at the printed book’s source code link listed in the introduction.
Challenge 1: Spaceship
Given the structures below, make the necessary modifications to make Spaceship codable:
rzjutf Zzoyohzih {
kul xaru: Lvbozz
xix htos: [VlavRijjav]
}
vcyeds PnihGaswem {
rez wode: Zyqevd
nir bere: Lgziyv
}
Challenge 2: Custom Keys
It appears that the spaceship’s interface is different than that of the outpost on Mars. The Mars outpost expects to get the spaceship’s name as spaceship_name. Make the necessary modifications so that encoding the structure would return the JSON in the correct format.
Challenge 3: Write a Decoder
You received a transmission from planet Earth about a new spaceship. Write a custom decoder to convert this JSON into a Spaceship. This is the incoming transmission:
Zoyk: Vwiso ihu ka xeghv ib geic mzvu, lifq ag inraf ob rcim wapsocq, ti vau’sl vois wi ebe kowpomecx gocv riq owcufiqb igk yizafuzh.
Challenge 4: Decoding Property Lists
You intercepted some weird transmissions from the Klingon, which you can’t decode. Your scientists deduced that these transmissions are encoded with a PropertyListEncoder and that they’re also information about spaceships. Try your luck with decoding this message:
The compiler can (as of Swift 5.5) automatically generate codable for enumerations with associated values. Check out how it works by encoding and printing out the following list of items.
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.