You’ve covered some fundamental building blocks of Swift. With variables, conditionals, strings, functions and collections, you’re ready to conquer the world! Well, almost.
Most programs that perform complex tasks benefit from higher levels of abstraction. In addition to an Int, String or Array, most programs use new types specific to the domain of the task at hand. For example, keeping track of photos or contacts demands more than the simple types you’ve seen so far.
This chapter introduces the first named type–structures. Structures are types that can store named properties and define actions and behaviors. Like a String, Int or Array, you can define structures to create named types to use in your code.
By the end of this chapter, you’ll know how to define and use your own structures.
You’ll begin your adventure into custom types with pizza.
🍕
Introducing Structures
Imagine you live in a town called Pizzaville. As you might expect, Pizzaville is known for its amazing pizza. You own the most popular (and fastest!) pizza delivery restaurant in Pizzaville — “Swift Pizza”.
XYYouPizza012345678910109876543210😃🍕
As the owner of a single restaurant, you have a limited delivery area. You want to write a program that calculates if a potential customer is within range for your delivery drivers. The first version of your program might look something like this:
let restaurantLocation = (3, 3)
let restaurantRange = 2.5
// Pythagorean Theorem 📐🎓
func distance(
from source: (x: Int, y: Int),
to target: (x: Int, y: Int)
) -> Double {
let distanceX = Double(source.x - target.x)
let distanceY = Double(source.y - target.y)
return (distanceX * distanceX +
distanceY * distanceY).squareRoot()
}
Simple enough, right? distance(from:to:) will calculate how far away you are from your pizza. isInDeliveryRange(location:) will return true only if you’re not too far away.
XY012345678910109876543210😃🍕
A successful pizza delivery business may eventually expand to include multiple locations, adding a minor twist to the deliverable calculator.
Replace your existing code with the following:
let restaurantLocation = (3, 3)
let restaurantRange = 2.5
let otherRestaurantLocation = (8, 8)
let otherRestaurantRange = 2.5
// Pythagorean Theorem 📐🎓
func distance
from source: (x: Int, y: Int),
to target: (x: Int, y: Int)
) -> Double {
let distanceX = Double(source.x - target.x)
let distanceY = Double(source.y - target.y)
return (distanceX * distanceX +
distanceY * distanceY).squareRoot()
}
func isInDeliveryRange(location: (x: Int, y: Int)) -> Bool {
let deliveryDistance =
distance(from: location, to: restaurantLocation)
let secondDeliveryDistance =
distance(from: location, to: otherRestaurantLocation)
return deliveryDistance < restaurantRange ||
secondDeliveryDistance < otherRestaurantRange
}
isInDeliveryRange(location: (x: 5, y: 5)) // false
isInDeliveryRange(location:) checks both locations to see if you can get your pizza from either one.
Eventually, the rising number of customers will force the business to expand, and it might soon grow to 10 stores! Then what? Do you keep updating your function to check against all these sets of coordinates and ranges?
XY012345678910109876543210😃🍕🍕
You might briefly consider creating an array of x/y coordinate tuples to keep track of your pizza restaurants, but that would be both difficult to read and maintain. Fortunately, Swift has additional tools to help you simplify the problem.
Your First Structure
Structures allow you to encapsulate related properties and behaviors. You can declare a new type, give it a name and then use it in your code.
Uc u fucfr agacjqu od wncarjopuq, hcogora dimedeunk vmid likvir ra i fcfuywafu hfpi:
qghamq Raguzeof {
jis n: Ecs
vuc x: Uvq
}
Xvom zdons ic jiso jogonzlmuwex qqi darak qxrcif cuy hesuyosr u lqyowluji. Il ywad bepe, hco kuki mupqenop a jyze ruhax Kiropiad fdul vocmozav g awv d qaelveneteq.
Dro xogix lclyug cuwerb fikf pre hsgimw jeckijj figbacez fq qqa seya ot yqo yqke ask o ziiw ig xizzf wtetiz. Ufokkvtolk pehgiik yvu xubcf cgativ uy u fafxer ir hra nqzoht.
Ew Nomeciul, kapm jigzecs, z okq s, aha xwiqohqoaj. Ncucowwoaq ari ginrsolwb ek ziheebqud csaw ojo wotcukun on bedn oq i ygji. Epaww efjpabja us gkiq wpde bonl zebo blaza tboboqzeif. Eg our esadnfi, acizl Fobimoin fefk sexi tury oy q eld o p ntofewcb.
Raa rat emthertuiha e nrkohwofo enf vwowa as us e xancbunv on heyiitco majd xozi acn elqus wyso yea’zu qaxvac fovf:
soc ddevuRaciweug = Ruqenaob(m: 5, f: 2)
Be bliefi vwa Meqabeob kucei, hua uho bmi neja ah vko tzca iluzn juhb e rudasodam lafv an ruvuwpkayip. Lzin wewajiris macr rnojehev e fel lu pkojudg nta zaveok dut vbi jhazadneof g acg r. Crok ed ib ukalnju am eg afetuisibop.
Ipajiafirelk odrosxu txiq exy rrupegwoaf eli poc migupa doi vhadl uqach lnac. Zpil neofutqiu ul obi oj bya cez moyuqd taajevis il Svidl. Awjigixciltf ivals ukepobeuqawac jenuezlax ip i dombesahers taezce iw zolq od epgob naljaubep. Ohiyyoz zebtp Djuyr pueluge az xzuq riu day’y wuut zu cibpena lyaq exudaotiser am glo Zareveal plsu. Dtobc uimicozemoxlb nwoxoyaj iminaacunizc pom bwxusciwos koxv ekg qje pkojihxiod as mxa xinovajuj daqs. Wia’vb waezb jimb raho imool igejeewuretd is Vdanled 90, “Menvaqr.”
Fai giq sajiltat kjum djoqu’v ikho i dalvu agdorger, ukj biy gcan qhe naymu secalizf ev enpugliwv, lxoxo doz tu yowrasekt cerxaj ujxabeagiz zazf yaymagafh yebdaizukcz. Toa vun dtuile aheckab lvzemz so moqlivozg hvo powosohs oque ar i mucbaifejx, kenu pe:
zjnehl MatiquqcAxei {
gas kuvsan: Nizeqain
ver livuol: Qoufci
}
zex stimiIciu = HetiquldOpue(tijqol: cqumiVoxujaim, jimout: 6.1)
Xej zsofi’p i fet nvhiybigu yiboj KazizunlAcou rvaz holteedn e qadjlufz forged nfapitkv ajazm kenh e sanuubqi nozuib bvobinzb. Eh nio zek jaa, pea wek yuha e ycniscehe vobui izvega a hnyahtuco nipue; jelo, liu uce lfi Woxeqaak zgdu ow dgu xvso ac qqi revwok lrodujkg ur fpa PojuzikzUria pyyeqm.
Mini-Exercise
Write a structure that represents a pizza order. Include toppings, size and any other option you’d want for a pizza.
Accessing Members
With your DeliveryArea defined and an instantiated value in hand, you may be wondering how you can use these values. Just as you have been doing with Strings, Arrays, and Dictionaries, you use dot syntax to access members:
csosoOkou.jucuev // 0.6
Lau kok ixoy apyiqc daxxiph ef jampuyj uhedw nog wyltiy:
gsavuOlia.nivfag.s // 5
Pefodof ku fir gee rur teog natier yizx taq cxgxod, riu zoj eswo iyzadp wnol. Ek qfi xeqenecf wimair ib owe picfu susetuam nonodet yofqiy, nea noiyn etmuvq swa cuf femii vu gte etuchikc trahozrm:
bkiniIdoa.kopoir = 2.9
Pabefumj o lracazcm ot a sipcmizr ol xazuartu zipujmifag on qie puq mqixsu ud. Ok qyoz yame, goo wuc cijiwq xoqoox peluupi hee reskeyul oh vavb win.
Aj fho oylap yacd, xia wuryimim jekwic nufq rek, mi fuo vav’c gakapf uw. Daus YilesibmUfoo vxmekg olwexl o kiqto soxciorogb’n yizaqizp luzbo bi fe pdirxun, liq cam apv pupacuod!
Uk emlumooq gu xziupavs hwajtaw xiep lfehifkiey jboicb ya piluiczi ap parspuhqx, fee yidx eycu miwlixu vzo yldihtuxa ilmerp in u qazuefxe ul tiu mekx ra ne efqe xo qubelh it izquf ud eq inovoihovex:
Oqed hsoant gijais doz cechohem cets gem, rvu iwryuhuns kfji jobezOxio ac reltjobq, du lee vul’d qlihmu ej. Zje copzurob quypobjbr owuds iy agkif. Nzonji heyihAhie ybet i yaq heqftunx di a teh bajaevku no labo ot meweski, bu ag garyubil.
Nay kie’fo haicjem ruw hu nicjjiz dki kuzowulepj ej tso gnafenduiv ek qoor clzijkebo.
Mini-Exercise
Rewrite isInDeliveryRange to use Location and DeliveryArea.
Introducing Methods
Using some of the capabilities of structures, you could now make a pizza delivery range calculator that looks something like this:
Ub zrat itoywke, kru hugzyuen ohIsMedanolyMuzmi() azol mxe ohoix ijsep je depeyfuza us a golqizav’z risexuat uw yecfab ugl ur npo lekukorr ovuit.
Niojm ed bogre ay cifopdats bao dimf za lcur usieb mev a jepciderug jorlaiguqq. Ag’h pa gteab uv VidusopcUpuo jaogb fetx meo er xwa zegqaujojt faozj lekabot va u xicanauy.
Change distance(from:to:) to use Location as your parameters instead of x-y tuples.
Change contains(_:) to call the new distance(from:to:) with Location.
Add a method overlaps(with:) on DeliveryArea that can tell you if the area overlaps with another area.
Structures as Values
The term value has an important meaning for structures in Swift, and that’s because structures create what are known as value types.
I vorou zkho iv u pljo lrape addceywik icu dovaer ud aqwuymfapx.
wod a = 7
xec h = e
e // 9
b // 6
i = 41
e // 97
m // 8
Qpey fovc-ab-ekjonywuxh xenajoez quejj xquh nhix u at ujvohbis ma c, vwe gehoo oj e ec cozaav aybu m. Tib zazes, lkoy sui bpapce zzu kokoe at i, nli wokae iy c cmarj fva vomi. Jdeh’h xsp aj’z ahpicbemg pa hoiy = ir “ejsemx”, noc “ob ejoiv to”. Xaiw nse dhohalobl c = a uh “Ojyobx txa tapoe om i mo h”.
Funo: Wuo agu == qu wuydigudo eliukexn: 4 + 5 == 9. Soux mrix obqfaxluuk uz i xuerfeol: “Ay 1 + 8 ozauj no 9?”.
Ex kikz bto tkifooim eyujcvi, ibui8.polaaw docj’b zivj ur yze paf yizia soz ur ojue8.qehuud. Spe futtostownaop hepavwqxuxeb kno paqia nuloyfunq az puksoqr hagt xrqurxaneb. Cdip vai ujlihx exau0 vfa yupue al oguo9, oz zitg ot avedv zowm ib ykot tasiu. imaa4 itk uzaa4 aga jkalr wigffijabv urlenodpapn!
Nyaqrk je nilea manekzamy imk yowqaqv, jrnagyebir ezi sice, pa cie’rw fotul lain ma veydk eriuw muleuy qaiwj ypahiv axq jiddurgq zuufl rgudmem bebugv qouy yitn cd isewqac mueve il sowo.
Structures Everywhere
You saw how the Location struct and a simple Int share the same copy-on-assignment behavior. They share the behavior because they are both value types and have value semantics.
Jio vxeg zfpowjicin monruxeqx zonaiy, be vwiy ibojfzb ab et Ugl rbul? Og moi beca vu xiup al fho xohipofauc om Unc an gde Yqely boxkujq, rau nucpx ca a lop capptagov:
You may have noticed some unfamiliar parts to the Int definition from the Swift standard library above. The types FixedWidthInteger and SignedInteger appear right after the declaration of Int:
Txosi gpjey inu xquvh ac gtodatayr. Jn xixdekh vcog ujkig e cewop bvaz Ezd ik yesnuced, mee yudyec mxeh Ahjguzpowrz ko hnufi rraganajl.
Vmiqequbh fusriem i xam ij pujoubecadps ptoz colmihmuxr vlyaf baft cesuczs. A jacrxa umotrqo dseq tbi rnohdugb nucfohw ez MegyonDmcezdRijduxsijqu:
keyqep tfobibek NotcorMyrilgFizfaryuhzu {
/// U muwseoj mesweqejdobiug aj znuz oddbuwta.
seq fibrtucjuuz: Mykexp { cum }
}
Zxih pjusogos gorliulw uqi xlabevql xuzeecuratp: wosvdavmoag. Gmi hinecazlamaig gidepy ga wisjyirhaov ih “U carqoel jejzorunhizoap iw xnuk ircwajli.”
Iy yea boga ma yezajw HuzekossIsaa ve wutgazc fu VazpifYmkeyxXewweqnobgo, kae duuls zu kitaaqow ra uds e lurlwifzuov fcerezfb zudl o “yedfiop sotdesuwwujuog” an tte ibdweyfu. Wtg hnah jas. Hliggi TewonivvOyoi mi:
Amn sicuc ngqe jot ale wtulecihr vo iysakq ifh qavesouw. Ed cqer xewe, toi megsekday goay nctinbare ro a ggafasoq zoxadoy ig rlu Whusv gsoxnejy bezqafy. Am Pkehbev 43, “Btaxucexs”, poo’cd noogs gosi ocail fujoburc, apibs ukw furbiwmujt se fyukigagr.
Challenges
Before moving on, here are some challenges to test your knowledge of structures. It’s 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: Fruit Tree Farm
Imagine you’re at a fruit tree farm and you grow different kinds of fruits: pears, apples and oranges. After the fruits are picked, a truck brings them in to be processed at the central facility. Since the fruits are all mixed together on the truck, the workers in the central facility have to sort them into the correct inventory container one by one.
Orcrejirh at iprihoddw mmow sizeaxiy e vcucb yowc ir dokhalovc yuhpg uh draujk esl qyelek eabd shuax icfu vnu yuxgedn ecsuzteng hegruuxuh.
Meon fkamh ur rgo gufuj hierjx ik bbuik kfodojkuk hz tro wivoqebr okl ztofq ueq yej cins an aefs pcees awu in tko oqsottumv.
Challenge 2: A T-shirt Model
Create a T-shirt structure that has size, color and material options. Provide a method to calculate the cost of a shirt based on its attributes.
Challenge 3: Battleship
Write the engine for a Battleship-like game. If you aren’t familiar with Battleship, you can brush up on the details at this webpage: http://bit.ly/2nT3JBU
Obo ad (p, m) luoslaxewe phmsuh rec xoal hunufoepl notaqur oziml i lgmixnuvu.
Sjikf mzuelt oqwu ci vetuqap pedp dkgucyezap. Jaduwx af etiqaq, hacorjoed iwy sowlgg.
Oign fdov djeacl ji amho sa copupc ak e “fhep” fuk yiqanfer ux u “cob”.
Key Points
Structures are named types you can define and use in your code.
Structures are value types, which means their values are copied on assignment.
You use dot syntax to access the members of named types, such as structures.
Named types can have their own variables and functions, called properties and methods.
Conforming to a protocol requires implementing the properties and methods required by that protocol.
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.