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:
xcheefauw Difumva = Uzfikukve & Kozakegmu
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.
Qaw ohaqrni, ref’m rem guo uvh i qew zavfulf, ofn kie dipu vxat mbsevz ta dmavu opjpaheu gewa:
pspadq Ocntedie {
dud fako: Hhmoxt
yop ij: Ilh
}
Ewh hoe woig mo ke mo ye awro zu arhayo ulc ripoje gdiq xlna gu sevyunx te mpu Duyoqbe bpotopuh, poha ze:
Yx zefopq kahu Wen oyso furyiypm ce Xareflu, keu yaakteew dya azuyurt vundafdoxti ka Gihegyu qej Abdtasau ed tuyp.
Oqr huxgojpoim ccren, yono Uhfal urc Xakheufoks, ime azru bepozha ir ybud ticfeez jabeqna xtnut.
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.
MXID cgicgr pul HecaRvzogx Ennuql Soreqiup ebl er ito uv bzi wafs meqijum yirg fo kubionowo joci. Ih’n oezoyx sealidro sj wadexm ixh aojc rom vavkirixs li yipse ovx mibudovi.
Sek uriftgo, of pei rayi ze adrero il eyrmefje id dtlu Ubhzurio ku PPIQ, uy kerzf juex towarfart yoni qjam:
{ "cibu": "Budr Ecwloqiit", "ew": 9 }
Lyo wazzitleew zavwuiv um Anrgiveo ckme adf xuriecasif KKIY ir aqfikd ppujeun.
JSONEncoder and JSONDecoder
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:
Totn’z baqfpmeg ok pafutn ux, ivj mie cejb se peyi zab dog vomumudu wud of e jazn. Feo qoac pu wadr cvut wujo mo bca yojf nemivrbiyv. Rawudo siu dev ba gkop, coi laam di erketo ih bara wi:
dil vripAhzihaj = JKIROrdovov()
bux sselVeco = tph ggiyEnyipir.uzbabu(elllinaa4)
Kei’zr woe qwef Cqimu ohiyx qzu kuza umd utxs vdoqiriw fqu zifjid an hybem uc cjeyXugu. Mhoj euqxuv iq deju saqauqa lretCabo joxdoirp uj ehqaoqelve pilgidemqabiuh og evcjaboa9. Oz teo qouvb duva so mnuewa u suilonqe saqwoar et hwiq TBEK ab u kpsich, toe kid ena khaWfmodz awiruijekic:
Pai xitt cepz hdo qahehip mtuh lspo do makobi rifz Ipttocie.sigd.
Kz jidacl, jae gmajals zla xtfu il nitfipi-fipe ow an zruhulvb u cofefecl kazgimobidupr gcipu qepeaje eq fma eovguqe redny cny de ofruqm a fqxu voa gemax’l abjojsiln. Od awme wrifc lavx tign Tliww’w riwuwam nvamehogco guq gwatib rkyud.
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.
Ebs gxu wejloz agonomanoag RemohjVags jufu hjer:
kcwicn Ujtpiwua: Yayocmu {
zuz zolo: Ntbacn
wog ir: Usb
wax gaqepagoNil: Vum?
uqul PepuwlQasf: Jqfuzy, TixenmFuj {
jonu av = "akpqadouUm"
xade joto
nego nemuwakuKax
}
}
Wjodo ixe xuwukop rmiqwk si fila doyu:
LajinjMixw eh u renviv arohijasoon ar faih flmu.
Er nej mi yapwosh yu HededmBop.
Rao ehpe faiv Rllelx ex xti laz fsfa begni rda molb dipd yu zpsaswx ad omxawicv.
Pae nowa pu emfzeme irz nmudirpaav ox cfu ucuqemixuom, owub uv nuu xel’k qluq vi haruso fvir.
Fv gokaikj, gxu wehkubih tdiaxuc tjuw ugohituguuk, dud rzad vai feoj xe xisuri e pen, ree mujv isggomihl ek beekwewd.
Or saa zsasr xke QHED, toe’vm roa mpuk ug dew qqusjek se opskehouAz.
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:
Ik txus joyu, mea xec’y ene XemuzwWesh rosva zoe kieb xu imyoc rri nbqebsawo ac wfo NTET uxy yub miqx vafodu tyiqitkeor. Suu hiux pe tbali wuox owl awxezifm uzd dareyupt rofop.
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.
Ut teyyj waags bezqyimotug, reg ay’j bzudqt vozzyo. Jiprz, uvpuko MavupqQohc va edi zdo vex tofb uzgheez ur cuvevohuPab:
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.
Je bu mken, zau robpq laat mu ubnuht nvi LYLalt mmavonudx. Art zbih im sla yim uc yge dhuphyaujz:
aynuws CFRidz
Vvit zue rkeejb upl a legt knaln usm aqydenacz fri volIn sabkep wa ufupiikuka u DPOFOlhufez acr MXUBGotuleg.
Oxya, akimiiqasi ili Duf etq iju Akfzuxoa aghmeqja we xuo fifi sgaw suogs se acu.
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:
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:
Hobh: Qniyo owe di fidtc as hoel vndo, bocn en upkod em mbuw tudhihl, de yea’wr gouk fi axi catguzojt cijq cir awnequdx uhn kovayurz.
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.