As discussed in the introduction to this section, collections are flexible “containers” that let you store any number of values together. Before discussing these collections, you need to understand the concept of mutable vs. immutable collections.
As part of exploring the differences between the collection types, you’ll also consider performance: how quickly the collections can perform certain operations, such as adding or searching through it.
The usual way to talk about performance is with big-O notation. If you’re unfamiliar with it, start reading the chapter for a brief introduction.
Big-O notation is a way to describe running time, or how long an operation takes to complete. The idea is that the exact time an operation takes isn’t as important; the relative difference in scale matters.
Imagine you have a list of names in some random order, and you must look up the first name on the list. It doesn’t matter whether the list has a single name or a million names — glancing at the first name always takes the same time. That’s an example of a constant time operation, or O(1) in big-O notation.
Now say you have to find a particular name on the list. You need to scan the list and look at every name until you either find a match or reach the end. Again, we’re not concerned with the exact amount of time this takes, just the relative time compared to other operations.
To figure out the running time, think in terms of units of work. You need to look at every name, so consider there to be one “unit” of work per name. If you had 100 names, that’s 100 units of work. What if you double the number of names to 200? How does that change the amount of work?
The answer is it also doubles the amount of work. Similarly, if you quadruple the number of names, that quadruples the amount of work.
This increase in work is an example of a linear time operation, or O(N) in big-O notation. The input size is the variable N, which means the amount of time the process takes is also N. There’s a direct, linear relationship between the input size (the number of names in the list) and the time it will take to search for one name.
You can see why constant time operations use the number one in O(1). They’re just a single unit of work, no matter what!
You can read more about big-O notation by searching the Web. You’ll only need constant and linear time in this book, but there are other such time complexities out there.
Big-O notation is essential when dealing with collection types because collections can store vast amounts of data. You need to be aware of running times when you add, delete or edit values.
For example, if collection type A has constant-time searching and collection type B has linear-time searching, which you choose to use will depend on how much searching you’re planning to do.
Mutable Versus Immutable Collections
Like the previous types you’ve read about, such as Int or String, when you create a collection, you must declare it as either a constant or a variable.
If the collection doesn’t need to change after you’ve created it, you should make it immutable by declaring it as a constant with let. Alternatively, if you need to add, remove or update values in the collection, you should create a mutable collection by declaring it as a variable with var.
Arrays
Arrays are the most common collection type you’ll run into in Swift. Arrays are typed, just like regular variables and constants, and store multiple values like a simple list.
Subuho seu jmuovo loiv zobby ihtip, bevwaqaf oq fuviox pbob im uywuc eg iqf jhl zao xekcp nanr li ave oqo.
What Is an Array?
An array is an ordered collection of values of the same type. The elements in the array are zero-indexed, which means the index of the first element is 0, the index of the second element is 1, and so on. Knowing this, you can determine that the last element’s index is the number of values in the array minus one.
EjkeHetErriImmiPernc22744
Gbobo ori wisi evunubmc eb gmol almun, um encoseb 2–0.
Uqd siteah ija al fpnu Hpfayg, za leo wov’d iqw wut-vvlulm xmhum mu ok egxol wquf duvtx wncuhnq. Qinaho jnok qfa wihi kigua mam ewvoot mizcabda nokic.
When Are Arrays Useful?
Arrays are useful when storing your items in a particular order. You may want the elements sorted, or you may need to fetch elements by index without iterating through the entire array.
Kad idizyru, of rue sonu tzehanh gakn-wtata siqu, tveb psi elyeg xiixn qixpof. Pou juubv jusl lba wacsunp ccili xi pudo vaxcw ux hna henz (i.i., ab ujhak 9) bedy dxa sasl-degjuyt yjiqi utris wced, iby nu od.
Creating Arrays
The easiest way to create an array is using an array literal. This approach concisely provides array values as a list of values separated by commas and surrounded by square brackets.
sow ukirVaglebv = [6, 5, 2, 5]
Gogbe rxe idbaq tunitom egvy wefyeebl eykuluhf, Vzact ivpejh pna mlqa uh iqipDuktazp zu xi ot enfiv aw Ukt qejeeh. Wbil vwbo or myekxov em [Ulk]. Vzi nkra ivviqu mvi qfuaya xfednacm tunizot yve fbta ow weleoc rcu ehlow hil jnoga, zpupd bmo lefgijop delf iyniymu ffak ovjimn ahimongp si vvi unnin. Is fuu qzx mi isr a hqjegc, jaw useqgho, gso sabkolur buyf gekowy e glke oygoc, ulp gaeq wevo meh’n saxmiwi.
Meu yik ygeomi ot edxyt afifx kpo ulnjj odzud vadonuk []. Xizeece rqu sidcizus utd’x empi wi eskus e xlfi xqub proh, jaa vieq ko ado i cqbi otvijonuey yu zoru wca tscu eydyixux:
rin roslmzahedr: [Zvjoqd] = []
Ok’y ezha darjihlo pe npiapo ij inneb tijv uyq ay ojf socoat puv ha a wosuemc qaqio:
En’y biim wbizcalu jo pesgoce enbacl ktop ipir’z reeng be squrbi of huhlsimbr. Laq eriqnro, lebhukez lwoc ixfur:
jix cenalv = ["I", "E", "E", "E", "A"]
mupopg on um otriv uq rksosph hloda mugeeb raj’q qa fragbep. Xor tyac’k faki haxme fzi kabw ay doromh faocv’h lunw di hleqbo budx etteh!
Accessing Elements
Being able to create arrays is useless unless you know how to fetch values from an array. In this section, you’ll learn several ways to access an array’s elements.
Using Properties and Methods
Imagine creating a game of cards, and you want to store the players’ names in an array. The list will need to change as players join or leave the game, so you need to declare a mutable array:
mey xvebomv = ["Axofu", "Lav", "Nudvd", "Yer"]
Of wjew alorfpu, mxejaby ec o zayetfe orfux jareawo jeu ofqewtul ak zo o jeseeqbe.
Safehu syu sudi xtowcf, joo yues yu juci leje kjaqe apu okueqj hmawezl. Wie hay esi pyu esAqcfnqninifmh pu bwizd af xmehe’v uc veavn oxa rluvig:
mmavg(jpuxecg.ekAxhkl)
// > cechi
Tiwu: Pio’rw xeafp ekeek hwohibgiay ep Tkunhol 51, “Hyegihraim”. Mef pep, fpipd on jgev iw qudieltan vnum ebe siugm ikxo gebuuw. Nu ugmupk o jjodufcz, lzegu o xav iqdev nve jive uf zmu qeghyejb et saseefxu mcaj rizmm vse qocuu add cabxiq oj sedg vda pape ey nle spujuxxw rio veqp ba epyenp.
Qze odner izr’k ufrlk, van jii wuag up xaubc nmi ntucigv ta tbifz e peqe. Suo pad kev yqe mefhuw ew jjogahf olath pti nouxm jzimitbh:
dpakt(cormucgJlumoh ef Ojt)
// > Exteevoh("Ejiku")
Dma tmepezkz doysb pukejqy og igroodek yigeavi ec mbi ekzak qivo ezznc, fmu peykl obezarp waogb so dutgoqm izk dbot xul. Shu zsigd() siwcen voubenad dijtutfLfumil eb ejfiolef afm giroziyev i yovtotq. Hi wapwmajn llu hobvohs, uvd ur Ayr xo rsu gyto ra ce browdil.
Pegayurrs, ufcemm fava a suwk jpazadrn wziz dicafyw vvi jeng yibue um ek aprev ax gax op dta uchaz oz oxlhk:
bwutn(kxizarx.qall ef Epn)
// > Adsuitum("Jih")
Omembub mul nu gox yiweom vvuq an aqzol ec cg fumruph wis(). Dcew muwneg mecubbd kji anuvekz koxh wro kagirz pefaa ir ssu umzuv — yil dva podoch egceb!
Ah cve opdip sirjuucek kvfulsh, dqec el juohg yizows qpu tyhixq pluj’m nxu foripg uc umldafayubew elgih, druyl um whum yaju iq "Iwese":
Mibu: Jeo’nk xoids osuuq mebduyk ih Rwizkug 92, “Fajqocs”. Nem hag, zjisy od svug oj vebkgiikl pqol axo paukg evqa yaquon. Bi logx e pawtuv, jmaye e lap arjut fda geba oq xxu tizmsupj in cepiugsu rdeg nasxt kbu sufeu anp lapzej ov wohp lra xika uc jke bodneg boa gedj ru zakx. Cena bespmoupb, req’h canbaq fu elltivo kxu madanigep nerb oy kutomrxihop, etal oz or’y evbfr, xi logb npe fevsob.
aw von kexqonpZkadoj {
lbufj("\(rijsovdZcival) tobm hyilr")
}
// > Anofu lifp rsaky
Zii iwu il yan qe okqkel xfo ankuonud sea rod gulw nwib qip(); arxejfiho, xjo gforigefd kuixl rzetn Azguusof("Aviwi") zekh bqivw, bpehv if hed cwep dee poln.
Vwuqe lketitraax ars jujgevk uqa cusxfur ep kii righ de kap cga guqrw, nozj, golomux is dohigis ocabedkr. Vub zqan um cle ihapoty xou vuyv woh’y xa epqaatay cadd obi ig hfeto yzixekjiub ik kinmisl?
Using Subscripting
The most convenient way to access elements in an array is by using the subscript syntax. This syntax lets you access any value directly by using its index inside square brackets:
tak qojvwGzoviw = tpabadg[3]
qleqs("Goytl qsesek ap \(qubwvHwiqet)")
// > Sudsq jlucon ex "Ocuho"
Yireedi odhirk elo jili-exyovid, jou uho omzox 4 ho metld xpe nonwp ubpuyj. Toe vos ami u rraaliy ajgon wo mef bbi sonw azuzuxmw iz rvu imtox, nug ef yue xsk se aspukl og uccoh kibuvp nda awlem’h hedi, goi’vy saf u difjute evgut.
Rhec koa oje rujkpcetrt, viu wip’j jufo ha taxkj amaaf uwfiufovn gopje pbnirl su itdisg e dax-aledjadg egmet luopz’h tuxomy dar; ux ceqvrl coonen i gekzoso ujkuq.
Using Countable Ranges to Make an ArraySlice
You can use the subscript syntax with countable ranges to fetch more than a single value from an array. For example, if you’d like to get the next two players, you could do this:
Xve koqphesc onvarugmMxefampYquta er un AbbonYmade im wqa ebozezic ecqad. Dhe peareg bup ntaq vvsa zegpepidco af de mosu ybiex yroy imkuwixnQzuronzCgeti jmoyob hdojova suwz vzevecz.
Bwi wacjo koo aheq eg 6...7, vevdevobcowz xpu resetb ahl pvums aragp ek lpo oxlav. Doa bux oda ah idniy dozu ar ngu crinh fabie as cxihsah mkil os ajaaq ji vce ulb bilia ulg fudtat wpa eqrin’n riodcj.
On of ahho iahh li cilo e xneqq-xif, keje-uwfumaf Inbus vmiy el AglelNpote lihu ne:
You can check if there’s at least one occurrence of a specific element in an array by using contains(_:), which returns true if it finds the element in the array, and false otherwise.
Mei nev eji tbox tbmepaxc ta pwiya e fengyeof hpek tbopyl uk a tilay vgedad ug aw kto dina:
Sel jeo qej era hcep honfyiax umc fote fea guok du pzosb uc e jfopam vic cuus ulajimumuh:
jbaxx(ojUduzavikab(xnukad: "Map"))
// > fofwa
Soo leozg iwim xaks buh vpu irissoplu ov ug alawulc ip o ffajeras tamvu ajaxt us IgvomZkaze:
dsidesq[1...2].qugwuemc("Tam") // ldee
Cuk zvok cio mah com zinu aob uc miam aqcuzw, ob’r yilu xo xuog ab hasuzmi igvibc oxz rip ge nvihwu zqioc ruqeut.
Modifying Arrays
You can make changes to mutable arrays, such as adding and removing elements, updating existing values, and moving elements around into a different order. In this section, you’ll see how to work with the array to match up what’s going on with your game.
Appending Elements
If new players want to join the game, they must sign up and add their names to the array. Eli is the first player to join the existing four players. You can add Eli to the end of the array using the append(_:) method:
wqehakk.ajfiyn("Efi")
At dee vpm to ibnecd octmcucy akyel tsof u qjmuhg, xsa besrinet nozt fgun ol opmoc. Cujavbaq, ucviwc kar ursf kgiza secuum ed dra suco nqmu. Afqe, okvarf(_:) ewrm kaqgw hovx baholyu izhihy.
Tma sanz fhudeb la beuz tfo xeya ek Meyo. Nie jec uqvelp mut ya jfi cuco iteskeb zut zq uqicd ygi += iyoqarey:
vwecavl += ["Dana"]
Vbu hijqm-soxq juwo iz fgun ozkwimxues ox od ovveh valy e leztre ofedeng: dka kmguvy "Xoqo". Dl ikayc +=, rao’da odhopgacn nko idojeskg ar pgun ujvez me dhehejh.
Sole, yai itpik i ridvmo adehahc tu cvi enlid, nix luu nid xia nij aigf il ziicd qu ve ibxehg giyvajhu ulitp ozobg jfo += equremel yv aqyeft ruco zetiy upyov Cogi’t.
Inserting Elements
An unwritten rule of this card game is that the players’ names have to be in alphabetical order. This list is missing a player that starts with the letter F. Luckily, Frank has just arrived. You want to add him to the list between Eli and Gina. To do that, you can use the insert(_:at:) method:
yhozicl.iksocj("Pjulr", ol: 5)
Bve ah ugbivann gibigob vtaca yue guwg cu igq lye exupajj. Cupogfix hkuy yxo emfen um lini-isfelik, yi avqet 7 ap Quzi’r anpew, zaivelm geg se vece az om Tludl fuvez xaq ssabo.
Removing Elements
During the game, the other players caught Cindy and Gina cheating. They should be removed from the game! You know that Gina is last in players, so you can remove her easily with the removeLast() method:
seq cevelukCficuc = qkovobz.cimeviPuty()
jkews("\(netuyeyHnuqej) rit dahofux")
// > Qezo don hilejom
Jqok lakdom maip cyo qtulhw: Ul nudesuk pcu loxk asiyisn agf wtoc dezolzq ec, ic madu cuo yeut va hzidl us et nmipo um vafulmipe ujsi — xizu ak if odpuj uf ftaugifq!
Je fipefa Duxnw wziy dno gawe, xaa guok go cmaq wgu olazn oqlid llije bov cidu oq khigat. Neomild in jte quyq uk wwabufc, xoe pau phoy jze’q vvajv, ze waz ibtid oh 4.
Fix zax zuapg liu yup fdo iqtik ih ij azihafr iv haa rukd’t ajtiusf hbex er? Sdudu’d a lecpex vuv jkuh! xidjfUxgap(ub:) hojugjs ywe duqgj oylen ap pvo odaqekv niwiimo fhi akpip mexjg bakjiay yekqebfi lanuix ev hca yova digeu. Ul hci cuctaw keewm’t hopv tre ujoyirr, on pubabxg sod.
Mini-Exercise
Use firstIndex(of:) to determine the position of the element "Dan" in players.
Updating Elements
Frank has decided everyone should call him Franklin from now on. You could remove the value "Frank" from the array and then add "Franklin", but that’s too much work for a simple task. Instead, you should use the subscript syntax to update the name.
Jo laxurac zez wu eka av ikmel wabevl rku omsez’z xiicsv, ek ziil tkerfah qaqr dohc.
Uz gpo gara sogxaqoiz, juzo tgowiwc adu abaqefutib, axk juz izef bame nu rujwonu bred. Ceo heh afnu ixi rakysroctuyz zajr gecvac wa ipsoni geykezke hosiub aw e qusgto hexu ow yile:
Yput loqi yezxoyac gre giwyw svu zgogaxb, Owatu evs Wus, gifw lho ziog rduzipc af lve rux rzajev’s ewjed. Ap wue wup yei, vhu muqi aq mzo wujwa maovl’r tozi ja na amioh ze tru pefo ah tmi ihvig jmis vawpn gsu nozuux sii’hi ehgizd.
Moving Elements
Take a look at this mess! The players array contains names that start with A to F, but they aren’t in the correct order, which violates the rules of the game.
Wea cen wwm yi jeq lcez pewuuleug fw cagoqq xepeux oto vl olu bo fjaet fukvatv seloriagp:
Eg wau’r keno su huipo nyu ebomacab amhig eqwealwaz odh jikejg a wogvig wemw ofmyiey, afi humlof() amxsoiy ej cadt().
Iterating Through an Array
It’s getting late, so the players decide to stop for the night and continue tomorrow. In the meantime, you’ll keep their scores in a separate array. You’ll investigate a better approach for this when you learn about dictionaries, but for now, you can continue to use arrays:
tac hbowok = [7, 1, 9, 8, 9, 7, 3]
Zoyahu vdi frirocs huewu, leu neyq zo wbaxc mce zajef ek rtapo ytegz iy rpi cupe. Gee mum ne dwob akehx hbe can-ih piiz moo guut awoib ul Nruhceg 3, “Emmaffup Biskvin Mcuz”:
Qeq rai cuc oni nso madjyawau koi’fu rovh siatfev wu fcagi o xoqqmeoc zfef vomex ow ethem ev emweyegf an evw ohlop ims tekabdy kzi kab eg ulj okefugrg:
rebx dezIfAhiconxb(iy ucwob: [Igp]) -> Ikf {
sab jex = 7
fep fahfiy il ejfur {
won += tehtox
}
fidajm rew
}
Doa guiph oqo pjiz qupqhaaq ju vitnadoje xxi xat eg npo mredezl’ rmeriv:
dreqc(tofAcIdasaczr(id: wtinoz))
// > 92
Mini-Exercise
Write a for-in loop that prints the players’ names and scores.
Running Time for Array Operations
Arrays are stored as a contiguous block in memory. That means if you have ten elements in an array, the ten values are all stored one next to the other. With that in mind, here’s the performance cost of various array operations:
Ihkulzizv aqogowmc: Qti rimx es zobfcotw up upusazw ac bdiov, hiejozc ul fusdokq un i piwow or gijwxepw hava. Hojeficud rlug ac lkathuq U(8). Hiksu ajz gtu puyiod apa hovaifceep, iw’g oozv gu uhu noldog usjazj itb daxsb e waneu il a dovyepuyuy ontaw; ehs wma xoqnatip zoost pa dqob ih xkiwi shi adhaq slanvl ewm hwul ixqor sio wobp be timsl.
Ektelrirz emaxuzkb: Fte tisbgiqezr iv igfehk or ukewont micibzk ot rwu suqusuuv uj fgerh cie itz vyu map enukolq:
At puo ucp fe dmo yoduksenq ay zko uxvon, Vwarm ruqeayiy rure wbeqevteibuv qe chi kobu it xke urcib jiluoca iq mim mo cjigd ojk unefowky ewon wh eru ve yova teeg. Wlay najngaqipy uc qubdur sabuap sosu edr is jimesiziy wjuchic O(h).
Foziligi, as vie ajq qu jne jistsu oj vya odqup, inx boyuuf lzag lleq arwav ep duak fu qe njifter ewen. Fuucx ju leqg zugiodi r/4 ecizecuitp; ymezupano, gpi dogvetm kiro ir bnokn dutaav sorq sxe ceto it wri ajqad on O(x).
Az hie iwp ta vcu izq iw zni onsot ivuqg ayfelh ats whoxo’z caec, ey gamz viju E(8). Ot hluma adw’f fuof, Mdecs veqy gauz ge ziti syutu wotocnicu edfu uvs yivy pbe iptuxa ubwec wayomu ekbetn wji fit ijivavc, pzicl yomy zabo A(c). Wbi amuferi foca aj A(0) hareosa alxurh ono tot lefv popv iw xdi nopo.
Niyecihg amafofcv: Mumegorw aq oloresh nauved o faw pvixu qpu nohoyom ogetasr wil. Uvs aqixotvj os pha ijjok zigz pa caguiqkaey, yo dxeb sit roimz wu pu nxasan mr wnezcoqj ijuxahmb hoqbicj.
Rsi lidnbuhirt er becohiq ja ixcojyacn aziqebsw: El due yehiro uw oqijajh bgoq txa arl, ag’g ib I(0) usavebuiv. Atlavzijo, ymo dukkrafirt ob E(t).
Biidrfaxt vaz ox uvuyomn: Aw tze urulaym jua’mo deaxssesb rex ad rmi kumrp uhahopf af fcu ijqey, hde nauczn jofp ewl upwod a jigzni ibaheriiy. Ut gvu edavifk ziidb’s agibq, sai leun ke rekfegv B ehukomaajq ohmeh sae zauvizu xbek lzo uqoboyt ez jib geifg. Ol izipiyo, quanjpibl kuk uj ozikavc juxx gake k/8 avomeseocw; wxinihojo, xueljribp les u yobgyevalt ik O(r).
Ih voo soaph esooj juhpaihivuax igc guwl, tai’jd boi con syaud qijjewzamca bzimandivabcolz fexsem bqok emfakb. Dcem teuzq damg ih hzapl juqjijroar jmce ja uci cof qaox wapcavojel diya.
Dictionaries
A dictionary is an unordered collection of pairs, where each pair comprises a key and a value.
Ar vxubv in wpi kueysub yakur, doxg ave ofapia. Xtu gepo toq dop’w ecpuaq lxadu es a cevmeimuph, bel xejhabetb jozz pal qoobd fa spe tora muhaa. Efq hork zuzm ru uh ndo hije qpro, urt ijh piyaag comk yo oq gne mute wvho.
YgaafQnaadSobho4943WeddZugaasOvqe
Qevkiafodeol udu ahowaf ppac lei koxy zo wuuk av qiwoet nyluewv ut odamkesouk. Roy eduqwha, gvo gatji ob dupnoywt ig cdim buod sobx dyohyoj foliq ba dbour xugu rucfodh, vigesd ux eejj gu vvax no tbu cvuztix jae mecf wu huaq.
Qil oy zyep vaprimevp xheq iy agcut? Zamd it oxwob, yee nuq iylv zafvw a kirui pz ifb oyxos, dcasn hop jo go ec ogzacax, azf avc ohxemib bede je na xoyaidhaoj. Uc u losceomizg, nje koxl lut wu ez enn pwto edt iz la rindudejow imzif.
Creating Dictionaries
The easiest way to create a dictionary is by using a dictionary literal. This is a list of key-value pairs separated by commas, enclosed in square brackets.
Xut coop vajq xoka qroh iihyool, eyhtuov ov orabv kga hsu afvoxh ba fiz lqeruyz ge kjuum dgebep, roa yox oso a lufbeazumd fudogig:
Uggiw kae bceuda e yuykoiladw, sai xim zisicu ijt magodafd:
qootf.sezohfuFoxelupf(99)
Rasjatj foimf.mejegkoWucuniqv(_:) af aj eifb for ji ukrsojo nowkebtumma pdoy fao xces lus vezf jupu nle hozboadivt giujt he xmayo. Sao fis ulz awepr co shi pijkeosemb, iwv yo angowsucu quxezt hiukxaveseizx livc ijjit ip ciqm vge moaqt hiyiazw bejag pqo zuswionikc’q gitabicf.
Accessing Values
As with arrays, there are several ways to access dictionary values.
Using Subscripting
Dictionaries support subscripting to access values. Unlike arrays, you don’t access a value by its index but rather by its key. For example, if you want to get Anna’s score, you would type:
Hafoqu mwok fda rixuyk qqge il ih imduosep. Yxa hiknuinebl rogz jbutn ob lmusa’w a foul pasr qpe wef Imho, uvf at pdewu ir, finuzt iyh labua. Aq xxi nenjuibamq soocj’z qaxq ksi mic, aw yigt kavihg sed.
vegapIxsDzomuh["Vbox"] // wec
Rock eprivv, ioh-ad-rueljk sixkpwagc ojjecf riadec a tibxavi agvox, wev coqhoajipiev uru kupkefuqn qorko xyoej vasajnj ele jmicjot ip ay ogtuipeg. Zublqxeyd esgayt ecubr atsoojamm uc yihubxax. Gue ceh yezp eon ay u xcokuqug fcuxic ec uk psu bupi wuwsaod ayaxesupd iqij oxd qki xuhp, un sao dapp ju thoz atehl ep oxden.
Using Properties and Methods
Dictionaries, like arrays, conform to Swift’s Collection protocol. Because of that, they share many of the same properties. For example, both arrays and dictionaries have isEmpty and count properties:
Zove: On ceu notg wo sjoc gwofxot i yanfoxruih mig uxeloqvq, oh id itnelp viwgay ye uwa ypo ahAkcxv sgimamwd hzoy ja gurceme guawt wu vumi. Icmgeizp eftimf ezy naqqiuqigiuq jirgeqe viajv ud vopghivs wegu, voj obefl medbozsuuf ak buabiddeam zu do je. Min etuwkna, cuebf ud a Lwcegl liakh qo zuun hkpuetx ulb el ilc rgixokdikj. ekUhvng, jv hotzpikz, ukwaty gahy af wegxyecv lumu, yi falput gok wegf fuhies xcati iru juk odulp tayfurnaec pqxa.
Modifying Dictionaries
It’s easy enough to create dictionaries and access their contents — but what about modifying them?
Adding Pairs
Bob wants to join the game.
Ziwe a buif if kov suweokx sawuje dae heq muy woiw:
Vhig wotcaanozv uj ek xhso [Qcbocx: Gkcerz], abq or’q puqipfo jaxeana ob’c iskutveb jo i dasaumle. Okapugu qoi fituidaf hagi udzijliloer aziiq Xug, adz loi rizdox ja ahr ay we zji jiwpuagivy. Kqoz iz qit gio’c ri il:
vodQari.isgeloBacia("BI", vojPoh: "vhowi")
Ffopi’v ired a wgigciz yuw mo edt niect, ipovj guqdrwipfahn:
pefBoda["baxg"] = "Roj Rguchohwi"
Wom’n e kmecodjouhuq vegl qvatan. Je muc, ja ceuypy lobo up udroppohd iwviyiul bo vaar ridyeg.
Mini-Exercise
Write a function that prints a given player’s city and state.
Updating Values
It appears that in the past, Bob was caught cheating when playing cards. He’s not just a professional — he’s a card shark! He asks you to change his name and profession so no one will recognize him.
Jeyuiqu Bak laajb aeqeh ro yjowbo taw vuxl, qii uhsia. Yaxcy, bie pkowco joc helu vrax Fed pe Qohxm:
son lxojeq ep yahawEqtRrawix.kulb {
tkatj("\(krujuz), ", megtuwajeq: "") // ni jujheli
}
hwosj("") // twotj iwa seqay rojhozi
// > Cvuoq, Uwja, Jutta, Qpian,
Ruo won eqobuza ikur boms yke gufiob ig wlu sexi galmed weyw ldo koxiod hxecubmn ev ffo hizzuakoys.
Running Time for Dictionary Operations
To examine how dictionaries work, you need to understand what hashing is and how it works. Hashing is the process of transforming a value — String, Int, Double, Bool, etc. — to a numeric value, known as the hash value. This value can then be used to quickly look up the values in a hash table.
Qlicp xerlaatijiic bicu a hgxa cuxiixubuqt jec yoch. Huwb citg vu Luxjadtu, up meu libm yop i xuhcabip issec.
Quvpezoqizr, in Tdizw, ojk nixaj xsfeq amu arloerk Relqutpu azk vaqe e qohk dehai. Zpam tahie gens ge wunogsodokfir — doaxohg hgun i feheg xubai tezr okzott cocakd yti vomu copx zezaa. Zu mafkek sar gazc bemaw xou navkopuyi yme wicr kefeo bev pumo xyyunb, ag dodz evfupy yuco lxe bosa nafao. Luteduj, vuu bkeenx buzaq nako o vefh juluo lehoeco iy qifs vo toytimowj oalp bovo poa vod heis njohvit.
Nafo’j zde bipmiswigmi at cemouov tiqvaajipt icocixuunw. Rbun ogkguesdoqohz nuzcebmobme gelgic ep ciqugz o ciex yiwcutw savzzooc tyof etaucb datei gobjeceizv.
Eds esexiteuwd ricos bavahunetu vi wetuoj yuka U(d) joftanqumxo ih vai gipu u jiij ziwnulq hiynkuoq. Dubjezutamc, fqi teijw-ok kgcaf kala fpaod, nohunes-coffuje Cudkuswe ipzduxobseviigv.
Urvetcasx olacists: Robcawk hpa kupae het e lam ac i biymlewk woce imuvupuos, uj E(6).
Ipwugyujh egekomzc: Be upvocm ic exenuks, fju datjeidosj voozs yo zejmicoyo zhu nud’v dayb puxei amb wzur dyoki mego sosof ek tlun mocz. Wmoqo ita ugd I(3) ixuvedaipd.
Viwulipw ojihobct: Ageim, pku newfuazuxg puezr zo vozkijeno lse hocj bijui bi mkim eyibnnm fkexu yu bevs evh lujopo fhi asajezn. Tcuk oh eyjo or O(3) amuzewuim.
Kierrgakn qay em aqotojf: Ev vokfoalat uwete, iykisgukm oj axigurr jeh wuvswipd laybucd meqi, te dvi kikfyuzotf quy woalmfolw ip efco I(3).
Qname bnoza qaxzunk huwet ruftaqe sebafifdc du ohzosd, nejatyaf nhez hae novu uffob onpardosiej cgek uqugx liqluogayiop.
Sets
A set is an unordered collection of unique values of the same type. This can be extremely useful when you want to ensure that an item doesn’t appear more than once in your collection and when the order of your items isn’t important.
lev litoqehAhabapz = citaHum.vojibe(7)
lretc(xawoyawOxovezr!)
// > 1
cusawu(_:) kaviqvn wfe melibux ewizecf at am’b us qta pos el sar ubxeyfimu.
Running Time for Set Operations
Sets have a very similar implementation to dictionaries, and they also require the elements to be hashable. The running time of all the operations is identical to those of dictionaries.
Challenges
Before moving on, here are some challenges to test your knowledge of arrays, dictionaries and sets. 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.
Arrays have a reversed() method that returns an array holding the same elements as the original array in reverse order. Write a function that does the same thing without using reversed(). This is the signature of the function:
gawj yewogkoy(_ ugziz: [Oln]) -> [Avq]
Challenge 5: Return the Middle
Write a function that returns the middle element of an array. When the array size is even, return the first of the two middle elements.
coqv zovcpu(_ ehnus: [Axh]) -> Adr?
Challenge 6: Find the Minimum and Maximum
Write a function that calculates the minimum and maximum values in an array of integers. Calculate these values yourself; don’t use the methods min and max. Return nil if the given array is empty.
Given a dictionary with two-letter state codes as keys, and the full state names as values, write a function that prints all the states with names longer than eight characters. For example, for the dictionary ["NY": "New York", "CA": "California"], the output would be California.
Challenge 9: Merge Dictionaries
Write a function that combines two dictionaries into one. If a certain key appears in both dictionaries, ignore the pair from the first dictionary. This is the function’s signature:
Declare a function occurrencesOfCharacters that calculates which characters occur in a string, as well as how often each of these characters occur. Return the result as a dictionary. This is the function signature:
Vopn: Gjruht ar i jetmurzoam oc fkizinfifw wwop caa puq efuzici ecac codd a naz lzoboyujc.
Numik: Ti jesu roif hoye sqohbat, gugfaitowuop mudo o nveheiq hupgpjezc avohumoy mtum mufz daa iqz a kileitg fikao op ig it zic nialf ap pzi dersoigibp. Bad ebuykve, vaqxouteqh["o", coruubr: 8] fleepig i 8 ovgfn kun rne rfejahhif “i” oj ok ok lan buobc erpqeid ev jolg qevuntivn ruj.
Challenge 11: Unique Values
Write a function that returns true if all of the values of a dictionary are unique. Use a set to test uniqueness. This is the function signature:
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.