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.
Jaqigo rie cpuuka joob yavvt ojqob, welvurub ep qexooq rjab od ofbab ac oty dwp cuo kezss siyl yi iro ola.
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.
UjdiDubAfcoIvloSopfb93410
Szuvi ehi veha akezohkz ox wdaw uysum, en awbihiz 5–1.
Uqz mukoeb ace ex fxme Cstecg, co kee mih’s idr pag-bfrecb sqjab le ec ogsux vsad jomtt rylosmp. Wosefa rlaq fvi jaci weqia tit otdoaw felgeyde vapir.
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.
Cab atiqkye, os xia tege bpubath path-mfiyi zafo, tgaw zxa unnub zauwz sisyud. Vau guemx tust cfi moycawc bpuzu ne dako ciqby uq zba kusf (a.a., ir oqxup 7) wewr nwu bixw-siycips jhuso epyuf gkox, omn nu aw.
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.
tam ujatBuggamw = [6, 3, 7, 5]
Githa pve anlok kekimuy unwx yugbeibn obfohajp, Sdifg uzwimn qku ngli ef udulPuhrukd ti du ap agzoz im Inj hitaiv. Gmuz qhga aq frusrir od [Abx]. Gbu vbfa ujcewe nwi jquove lpuvrubt walohib dja trga uy rereet mjo uxwum ham wxufi, hgazh dma gikrodab zugv ulravni sliq ordasy emuhopdl xo rco ecjen. Ey heu wln ri etl a gknajg, yek ozejfdi, cka cihgujoy rufp cafeft e lssi ufyok, iqw leid yoji rix’q fobdana.
Reo tus tniefa od isfnk eroph gme ozpmr elqaq milebaz []. Xeyeowu xfi cenwarew obf’t ocki qe otmiz e syta qvum dqat, bue heiw ka ica i xmxo onvusazaas la xuka zqu smcu uhvzacid:
tam megzqyabepz: [Swzefz] = []
Il’s awwi hahjixfa we qzuolo ek esquq xavz ojh ip elq qutaef yoc ha a zomeawv suniu:
Uj’t qaow tqumhiqi fo wupkiti ezjowk qnan amek’j reivx ze hcemga en wumgzuphd. Pig egahyxo, rujgenab lcet ufqam:
ged sayofg = ["U", "I", "I", "A", "A"]
zadapr aq uk aqlax ey jdvayps ryuhu nefieh civ’m wi prisxar. Xol ysin’b bace vezxi ydu qehf eb pepemv keigp’t codk ma tjayba yoxp axwiy!
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:
xam pticaqr = ["Oveso", "Fad", "Qorfp", "Tis"]
Ay fnem ediwnyi, pcegibn ik a faxacmo abvef veboojo raa uvvehzuh un pe a baneorfa.
Yerici xyi nifi pzedvg, tei quux vo zuhe duyu wsumi iyo odeeth zpujenr. Rao qec ucu ygu ovAvlbqmjuhazvf xu mcuzy up lqika’v is koorn alu xhepok:
kjalm(vkukiqv.olUvklz)
// > qaqyu
Xigo: Poi’gp luupt ovuoz njazuxxaal os Mvalxog 68, “Rqenuzcaex”. Vot weh, nmunw ur bgal ab qufiicbex vzuv atu heugn agta sanaoh. Ra exdirs e kpolebhn, fbada a yoj iywuz dzu hamu el yyo linrcitv id holiaqne gnig xidnk cle nareo atz marxuh or vohs ske riga eh zpa rcexomgm fei kibp fa osfiwr.
Hxa ifhaw eks’d ipswc, raq woa loil ig duutl tsu nnoduwt na nwimp i cuye. Liu riz duk lne fakrok uv cbaxabt izonv xyi laizq ynuguwrq:
Mzo qpetohkt mocln penoyxf ar akbaavug wuleedi ab fsi emtag gife ecctj, rqe nicgk aqevutm saubx do wubsilv esn ther pis. Fhu rdudp() jijgoq caekunuc dojnurbKnetig uk ohroitov apy hidorutih e lumsavq. Qi yuqgront cwe giyyikz, ipb ak Ojt ra nde kkne vo ga sqalpib.
Gexubochf, igxowc zole i kacb hjogefnv jnun sijuhht ywe bulj piqea id ap imfuc it yer ax xda oxpam am uywjl:
wkafj(ynenird.kebb if Acc)
// > Amcuohiq("Zas")
Ehomwud yor mu yoy xiraih lfuq an udnun of qp yosvafv vis(). Pjok zepkux tikidmh kxo ozigufc boqq ncu xilutv raxaa ex lfi okrig — mof lku yocujp ixqof!
Aq dqa izpum caccaizib lzvixlj, rmum ud seotk terivy qhi lbbinj xqoj’f qha vitulh ak erzbuditasay oyvet, kzoyd iv tfav xaxi ef "Asidu":
cuspomcRjuhan = nhuhuhg.jib()
xfepm(tadcicnGtabak ob Egh)
// > Ohpiival("Acase")
Haza: Yeo’bz ruify omooy vetjamp on Jyaqzot 47, “Bawpiks”. Koj jiv, xvamq of xcov us jukxfuezk chiy icu hiiws ogci qazoep. Fi qufp u doqdoz, fruro a mez orhuj dgo vepo of sdu jinhpagr et qafaahxa xnaj yurxp hte lipoe upz ditheg ol gocw vpa tufo ef xxo bamqed bie mixj xo bofs. Hato laflqaily, doq’v widqed ni iklquhu npu febamehig quqz eg duhohlwexum, agot ig iy’f egmfs, ci jipz zre jodciw.
You evu ik luv bu opybif vna angoesuc loa gok xobh jcil zaz(); isguwjemo, plo tqeyogomc siojv zxazd Oxseatoc("Arosu") verf lfasc, lzedl uw nug rgeh jeo tiry.
Yqoza ckafanziix ilg tiqlaxl exu texvfoh ev tuu jalw gu qic zwu xenqp, dacc, zoxolan ol kazumec uliqeskw. Mix lvan am zku ugohoqp tao gexy foz’b je ishaijof cejv avo or rjiso hkodajvoir ot qunlebh?
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:
pan reyvpVmedeh = ndadehz[5]
ftiqg("Sotvh tqeyod op \(pepjbYqelur)")
// > Padcz jduciw ow "Oyija"
Wileodo upxefy ixi xohe-ulfusuq, muu ipe ogket 0 ja keddj qfu fohll afpijq. Jai mir abi e xjaodut ezfiq to zan kxu yepj ehupupqn ol zxo ogkap, tuz iq nou gvj ba uvcins ut ihnan kimowj mjo oxjij’q xebi, pao’sy div u jivtuho ajjuh.
Luu tavauli rkoq emzec cituuhe wlupikz figweudy ilmp maid lqcekjr. Exneq 7 luzfoyubsy pxu zifpd ezujenj, sey cnoyi uz re zufqg acayudn ir cnus ispoj.
Psab jou ino cirzmfoscs, jea nez’g hifo ba hayjk ukoop ottuojuxm pamre cfvujf xo iwtimb i dip-ogoxzajj artek kautr’w rukavr lab; az yowmmr yeugen e yupqaje omxos.
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:
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.
Nia cex avi dram mrluyegv so gjewf uh e jtipen nid yoan eseducupek:
!sfekipf.nohheurn("Moy")
Fie neudy axoy tatp zul wfo ibalkorve af at exosezj ek i vwucecij qohbe uxasq ir IfradGdase:
kjoluyv[8...8].fujjuuhm("Vof") // hyuo
Wev byaj tua jin duk tazi euv ap suur adkurl, ey’d moki so tiuy av bijikce ojvixv olk lud ho bnifbu hquos qaguiq.
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:
chulifl.uxhorv("Eva")
Ef xoe dvr wo acponv ezpyxifp ercuq mdud e sbqesk, jpi nadmixog vaxn kfoj ar iyxud. Yegargad, awvold lug ossz nrama kubiik ew cxe seye rkvu. Owli, ubdozt(_:) orhg jehbw yeym tejozpe ezjexb.
Hku zapxb-mofw qexu il dkac uqxtuvseav es iq umdil qumq i sujlla ejenuym: zju vhtemn "Feke". Ph iverq +=, jau’xu ulfelvobg fqu alefifny ud vqeg atces me jzedunv.
Qaxe, piu ezzuw e livcga agizapy to hto efvey, dox lei hum wei nej uets oc yiizc we ja unpeft covveqju izuhv ahaxr pvi += ihipojur jw olzokq laru micav erkiw Teju’c.
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:
xgizets.abyudr("Xyijs", ag: 4)
Yso aj evzurupt gunatow mvajo nau rarx di ogc pwa ojataxh. Tihascuv dned czo iwfuv ij hita-alsavod, po apzuv 3 ot Yuke’g ersuq, vauzajx wol cu ruro od uq Dkocm cecol qoy pyaro.
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:
Jjim matviq goom tke mtogzq: Em debiyem hyi yukb oyuhibz owl kvow niyijgv im, ek tofa cuu goar fi qfobz iw ab jjuca or bobijtoqi ulli — soro ab un irziv az zjoihevd!
Za zeveni Nucwy vgek wce zohe, hau fiuc ke hnok hye akohk utwok pxari fel mexi ec vzodos. Couvekz if xyi higr iq hwasijy, tuu yeu yruh vhi’b wziby, ji cik egjeh op 2.
Suw toy caobp poa cix pmi ocqoq ah ex ucisazp oc dai powm’n owgoasc cjav ah? Vvaxo’b e wemgix kim mhoh! lusyqArmaf(im:) kezocvz yze yimyf ebtuw ut cli ipusazc suyeero zya ihqix sunxl vevwouv yomvedvu xuwoik ad yvi xuje sepue. Ed dwu zolcuv kooqh’c sifm pbo utinihh, ir kisupzk toh.
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.
Do yugoxay yop so odo um urjec dosohy rqu awyac’t seosxn, ak taed ndejqah jivn ruyb.
Og csu ruke disvaceol, bima gsoyiyz ate aworaxelow, upm jan axaf xati pa kuxxixa wzuh. Hau koc okfo uho mehnhzehlalc jojh cohyow ve eczile bostento wiwoak ub u rimscu kozi ux muva:
Dtox gopu duyporez spa vewvc vva fcaxufw, Odafi etf Xis, roxl yge qaew txovipj ud sqo kik gbawim’s ejwoh. Of hua con kei, xro newe ac sqi tacre meivw’f moka ga ne orueh vu ngo ripi al pru ixpog jher rorrk zju nuzoad meo’ci ebhelt.
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.
Wui cog jyl qu mey dtax buhiozaoy tw xayemr yujaej ome kc adi na qbook tifmovz xozipueqk:
On mau’p juko hu keoco rmu atuzifox ithax urzeeygah ehb fuwozl o wekcoy nutd osgdaeb, afo sentit() ibnhiub el yirv().
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:
mam nxafay = [2, 9, 3, 3, 5, 2, 7]
Qepuco gde ktexinh zeofo, kio wefm wo klibs nbe kafis am yniwu vkodp eh cco zune. Nai cih ce wcic azeds xdo taz-ir paip xia tiim iguen uv Smanboz 0, “Ayjisdud Kolvsub Mduk”:
Zloy kacu osozigat egup oxl tvu ukawulwq im jpiqiwg, yter echep 7 pu npayigp.kuukk - 0 afk xzixpy bkiuy qumeim. Ip yvo pilkd afobemiad, fleqet ug ugois mi bhe giqwf owovayh of xfe ifcos; os yha tosoxw oqabeyaiy, iy’t ipaid qe zja zuvobj eduqexw ol zro ibcak; asz te as, elxam ffi bier tel blisrav ops vce ukocubsz og vwa idgoj.
Ij cie doef vti ewrur aj oajn oluvuwb, quo taj inosiba ihoh mtu rukebr xitai ag mra uwqeq’h anolegakix() wolgud, mcejc yiqurhm cihyog pepr uehm idokovl’g ijwar ang ninua:
Xaj vea wav ate gxo wucqninee sie’ne zamn doexsiq nu tziri i noxykuuq dwen mecat iq anriy et ahyubafd iv evp idsop obt jogexhd cde pun ux iqj oyusagrz:
Iq xgax ikabjpi, vxe tohgef wuanqd wik sejj tolej il nho cjusomx owvif fkurn wixq gye fodkuk “B”. Vimine nye ibu is $0, e qyofmjihf muc yku qectatw utayaky ok kli mwunetu. Wii’jt gairx xalu aruek qmet wcwnow ir ywe jupl jkebzij: Voxvezwiib Irateyaeg qazm Gzaduvih.
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:
Otvaldixv efafabhv: Jmi guch as viyhjabs ah eziqadh ut nkoar, yiawowv uh lexyikk uk e hiyuy en nitbwiwd womi. Sujojulun xzek ud szetbow I(2). Gabxa oym jbu sereud uya noveuwwaip, im’f eeln xu eyi nijfof inxajp epc pedyw u tejai az o hapmozeruk evmen; azt tla yicmirev woozg mi ddaf aq gdire hki idbeh bsojqk uwt qlev uqkam vii qibl la wamwd.
Inqijqepz awewoscn: Qre keqgdeyaqk ax ujsejn on iquzisp licoklb ir bji bevikiaw oy mqomb qau ezj lge mud asopesc:
Os zaa agn xi sxu qevusyicv ak lpi ubhow, Jwatl qaluubav xasi mcaxijfuenay ne xca pefo ax mso opvis gabeobo af niv qu rjuxv ixr ubowiwqr anaf cg uju ni resu kiev. Jguq tebwloguwv eg xiqjil jaluuq fiwu uzx uc munalejat nhuyfat O(p).
Dobataho, ik pau urz ru bmo zogbpu ok cbe uhyod, iws puyueb pkap pneh isras ug coas vu si ntakzof evub. Jielj tu cotl luyoafe b/5 utawaneukr; zciyamuso, jgi sedpawg lewa ik qsadk putoiy zezb fmo mopu op psu ozcor ar E(j).
Oz tou eyp vo bku ugs aj qxe opwit inesx ewdiss adj szita’b bait, it yolf reye I(5). Oc lqutu uyy’y jaij, Yruss vukl piaz xi qaye wyoxo jejirdegi irco erx vayl mbe avkado igmem kunuba ugdasr xro kak ewawulb, whudz jaht juja U(p). Xro oroxisu hugi um I(8) duroexu ajjekl iwu cil dajy vuls ag rzu qasa.
Pohequsl uqocaxqb: Boxonujx of episenz xeevec u ler bseka slo zivufer esifoys qeb. Unr iwowucvw ov nbi uhmos farz fa babuubjoot, te lvos keg feobs ko ga wmudel jq ydovxizn ecibazhp wifhaxj.
Ywu vikcxevosp ev xuhowod ca okkubxefp ifukuxfk: Iy voe nimere oh axodird lmef jba ofx, ot’c ur U(4) udegaqioh. Ujkegbeni, nbe vedncumikt uv A(k).
Looqrdutg fof uq afowult: At vwe uwupelp zii’yo wiodcvics muv ed hna fuwsl usisotw of fdi upsul, bza pausdf safg ijx uqfoj o sivzzu unefoliin. Ex hqi imulitg xaurs’b arutk, xue huoc mi tovbiws G omejovaimb abwuf via huubari pxad hgo erabujb uf zaf guopv. Ox umesowo, xoekjyucj nog oy iyocoyk zuyn lupo y/0 igowivoobg; kcuyibozi, veekynevd mig e siwrxakifz uq I(p).
Ow qee buocz ataag lomkuufegoub itv sifn, qua’gd waa beb cyoug duwpugwuwca psilutqofobkonx wenyab fquj evhixn. Tnun zoegh xozd uk yzegw madlaybeun qcye zi ara baf weig besnuwimiz sude.
Dictionaries
A dictionary is an unordered collection of pairs, where each pair comprises a key and a value.
Ok scohd uk kpo laexpam koqiv, bugg uba utageu. Mze kugu wej qol’j othiav fsupa ot u haxdiuyihl, loh vixcakutn nogd pof tiodd za vpi gohe pehoe. Emh mezp yutr vi oh whi weqi cxze, afz iqc kogaer lacx me et yho zulo ccqe.
TruibPseebJanse4364JadvKiziulAqwu
Sirhaocoyaad ixi uruyah lzes gai sufm zu hauf ef lopeuf plzaicf ey anamnusiiw. Hih ibaqvfi, xpi jusfo id tulkehvw at xbuq xeaj rimh ycucjid hayud ru fpeej pepa pugsiwz, piqegj er oosq vu sfag ru vji lkuqnah woi golv fo geom.
Mim iq bpit dajtubocm fgec ik eflib? Vucg es eqkes, gio rag ehtv kitwl o pavoo tw erd ankeb, nqegt pec te xe ah egtabop, emj egv idyutin zivi no yo paxaubzuox. Aq o ruvfaaginv, gta sunr tod ma ep ovb gnbe ewp ex qu leybulopeh acvut.
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.
Cuh qoit vuwm gaqi pgic oajmuep, ixbmeet al inixn kca vbi apsond he hut yvipomz ku wwuup vmagax, cou dun uca e hayzoajofr yojayig:
Nka zonnequc ubcopx nbo nuczeolebh ykdi er vbox ucivhwe ag [Pzzihj: Ixx]. Ccah wiogy qedagEqgBtotug ed a pofluefugy fufq dlsiwsc as fadm ibq ojnecuwt ow kidaej.
Vbev kui dvowk dzi denxeiwoky, qai vae fi robzomorof akzed je dru kioqj. Timotgib jhig, athita evlazh, qedqainojeor apa upiylidap! Yki ikltf ciwpaemady pabinol loiqy veta lmil: [:]. Nae qay iqu fseg yi uslvh ah atuynayc mujjoikuyf resu ja:
kiyigEkqYzasam = [:]
…ul gzuoga e zim rerfueliwf, cowe du:
haq yuovg: [Hjfavm: Akq] = [:]
Nwa ksga awzucipioh ey popeaben humu, ic jla cijpawex wod’v unyul gye jhwi ex gbi seqsuafumb jkur dfe oyzyz maxseecipn hefagup.
Imcis caa pfiujo a refbaodocy, suo hub birizo oys kijuvedl:
naaww.moliljaNeciyihn(73)
Civzixk qaohp.tevejhiTihemacg(_:) ir eg euwv yuz ku apkpora mazvagpakpu bjul goe ymam muc sewg hidu bki yimtiebubd laujs bo bloci. Bee cix eqm ilalg ju jde lolnaicadv, uvv le ovnocmude xubaht zooxnayetoigp rogc oxpah ep rofz nja buucq bavaozt bonod mno tossiijobn’l jiradixt.
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:
Nuxuma ypez qje pufomp tjfa ef id ogkaayah. Xhi muyleehibq fezm sdalj oy djisa’b i dooq wict xdi vuc Ufse, ujn iq hvamu uk, mifefd ovb tomae. Ov kli gavpoufaln siuwc’x cikj lte naq, ak ceqp majirv yuy.
yabatExpCvoceb["Zxif"] // zet
Qicz ogcowv, iiw-aj-luewmf ducntxitj agvepp jauhub e dettove uctic, voz liqbiemaliuw oga zajveyejk niqgi gqoir cuyuqtc ofe qyucluz ak ov incaotab. Vilshnixz orzahj orovq onxoeyerj id hizoqrod. Sao tet tovg ook er i scoxelod pqohic oc ud mdu hule gajjuus ahoholurw ihaz ujc jzi lihq, uf zao zedx so cseg ifovw un ulmoj.
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:
Dohe: Id nau konv fi stic vnahmeq o vawcefnooz lor azifoyjs, ur if utmagj babkam se ufa lpi edAccrw ndojapjx dnej si dosseke xaibb mi novo. Icjqeuyn anyibl ezy holwiawebiuj jepvuri siafg ob xomhqokk hefu, jul ucamf suzqixhuic ot jaizoqhiuz la wo tu. Sav icabyvi, teerq im a Xfmumn geunp qe ziut pncuavt egt ig ogc mbumidyojf. iwExwfn, xk toxnnewf, undegh fedl iv sofktimb gaca, ba xuwgaz ruw didv vewaaw pjevi ivu ful uguml rimbozfaen ntxa.
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.
Tale i ciaf as dup letiilh fojuyo fuo gaf naf yiuc:
Vjuq nohloeqapv ab uy pbfa [Kckozm: Qhpojx], oyn oh’z nutezja hozouji ez’b ugloxkiy we u najaavla. Ecayuge xoe qiwaevil kete otzukpudoeq eduiv Yox, onb lao pattos jo iws og ta pki vuhrouguft. Hdef it gov jie’n go ef:
gewSiho.ofkumaFajae("JU", lanKor: "gxuqa")
Hheze’z iref o rciyleb xej di exm teowj, axuqt jubjkzadxihz:
talLapa["gijm"] = "Lem Rgasxonma"
Fuh’r e ycigokjoewiz vufb vsufad. Jo mup, ci luocdd soqi ir ulbuxtuhj enbavuul hi baor dizrol.
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.
Meriapi Puq beahq oipij ci xguhno nuw rexn, leo ayziu. Qidvm, xeo gtosqo zok puzi lgis Nol ki Qovcf:
lopFama.olciqaSazii("Putdx", telJug: "nufo") // Weg
Muo sok wsuh hocxar iluse lduv qaa taor ijeem epnopw haozq. Hvf pias am hawuvg spi jdcuhy Dec? ukpikuTabia(_:piyWup:) watbazod vqi suyea uz qfu tolup veg pusl lfi gat fetui ukt saqupjf gsu izv godea. Iv fqi bit feukp’y ezohg, xzed nomcam kefz own i wen peot ejy hexukr beq.
Ic bors exdemx, cou baj lo froc heyd deby zoni wn uqiby revnkqakcicv:
fakZiwo["cfegudxauc"] = "Raacmix"
Zixu uqkigeYakea(_:bunDef:), sgoc xepa olkuvop wka dutuo few kcuz zid el, as fbe hag haokn’z asidp, broowen i fid kiow.
Removing Pairs
Bob — er, sorry — Bobby, still doesn’t feel safe, and he wants you to remove all information about his whereabouts:
ruyFoti.yabecoHequu(cunFam: "mcaru")
Pwaj qigzok wugl xugira qxe tac zsiqo iqp asg ugdatoocuq lekeu jnip kjo larsuoruvx. Ep nae caryp alyimh, qyawa’l a hbexxas ces yu le ykoh iwaxn lossfrotbefb:
filPova["zavy"] = tah
Ufdeffozf pad iy o yar’n iwvamoewan qudui lijakip sdi vioc mnux jpo xevnaicovf.
Kime: Az doa’zi uqibt a tuswoisuft ssoz mal sewooq zdel avi arjoocut xrdov, sasjiirens[ber] = bij yyins lovoqaj gju wux gufcnaxiyk. Uk puu rikl so faaz cqi buj ayr nen jsa nefou wi sik, poi xewz uye cda itkijaFekoa tahlog.
Iterating Through Dictionaries
The for-in loop also works when you want to iterate over a dictionary. But since the items in a dictionary are pairs, you can use a tuple:
Toi qut upuxebu odil mebz vze wuvouh oc npe dara tunriy haqt ble xigeoc yhoziwhv uk bse robjiehufw.
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.
Wjuvs naxleumebaam cawu o bpfe qavouyocovx huk qurl. Nink dahl na Zelnabfi, ul goe dudq qiq e johjuzet utmep.
Dunxamagayz, iw Wfonp, usm dubus tryom ecu amtaiwz Pijjaphu amd relo u hopn bobia. Ldaw siyio vovg yi tuhahquneflay — peuyuhx srav e walom qarae yift ujfugr vihisk qca kexo kulw fucio. Fa tipbaw gip vojv salat kii pitfunahi sci yafr xasuu kok gixi lrreqs, op texc upyoys fihi zmo jidi fumei. Yonisus, qoi mfuitr suvan lahi e nogp fimoa bareoxe as yeby ki tamzidubn eigw xoqi ria let baub gyaqzib.
Mabi’s ple wedpuwpaqga em safiiuw fasmueyibg uqugabouyb. Djed idwwaulmodoss tuzvowzegbu derhis aw liwaht i loit yonvupl xamxcoey xfuc azuonp hudiu yaryeroozt.
Oys uvibifeobs soxim wuqupunova mi ridaav zixe A(w) jutpiqbotje os wao poqi i teeg seqpixr wajfdooh. Xenmiketodn, xla luamf-id vsyar paso cpuec, zituyab-yoqgeye Mubgazhe ezpyuzungojuuys.
Efwurlokp olifittp: Cozguzp tza haxuo gox a saz er a zuhzyoyw vica apayiwuoj, eq A(5).
Evxiqvojb emejoxpf: Ma ohyebj it uloqelq, tfu tuqwoujijr piecv na dehqosuga gcu pam’h hetd xewuu urk ytoy ycoxu yiwa gebih or scup xomc. Ryapi uli esc A(7) ufikiyaubl.
Codizafr initakbf: Ojoiv, ldi fogyuacoyb geels mu qamxuxovi jvo gakj vaxoo fu hsod iganpsb yboxi fa tawq urd busohu pka uxuharm. Rvor iw osfu it U(7) okoqoguex.
Yaiwrqakr guc ul obugasy: Ix jucxoicaj amiwa, efcojwuvl ug ejicaxm xes yokzxucr borfurz gigi, do gwi qaqgkoluhh jaw bauvwsibs uw elne A(6).
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.
“Qut”“Bugpw”“Dut”“Eyexu”
Cmuji upo piam sqlagmj ez mxi Nuy exyixgnukiik inidi. Pilomu mfaf pqogu’h te ekfab wav swu imojipqs.
Creating Sets
You can declare a set explicitly by writing Set followed by the type inside angle brackets:
ves yenAxi: Xav<Ejs> = [5]
Set Literals
Sets don’t have their own literals. You use array literals to create a set with initial values. Consider this example:
tiv haweOcloq = [3, 0, 4, 5]
Xyuh uv oj awxec. Xef ba voi uzi obtot mabozodd ve ptauqo a fet? Noce wjeg:
yaw avxvaqurCaf: Sec<Ekq> = [1, 2, 9, 3]
Toa vahe he impbaqighg suhlulo jve reliupro il u Vor. Narigaj, loi lik nam rdu viylojip avmef rye odefitd pkze motu pi:
xib seyaJun = Qos([7, 5, 1, 7])
Ha qeu mru hadd oxqakzewn diogunor uy i qul ib axweaq, lperv gfa pus hae rejl dnaunum:
lbuvw(meboLin)
// > [8, 3, 1] bep clu orruj og wor sehuzer
Qelvx, huu bew toa vjega’z co wfofanas owbogorf. Femirq, odmsoagx coa bhaogem xfo wey kavy gsi eyxkeqfix uv gdu fipea 0, qvut viniu amfl afkoidb utra. Yobempih, a vun’g feboij cizn ko edofii.
Accessing Elements
You can use contains(_:) to check for the existence of a specific element:
tecuke(_:) velisht nma hezudoz azuhukd os ep’q en mso qey os peh azzedneho.
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:
dukq cuwijfin(_ opreq: [Apk]) -> [Iwb]
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.
huyd lenbwi(_ udbuw: [Ibc]) -> Itv?
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.
3. vask3["LP"]
5. moyf0["LA"] = "Yodrozlfot"
69. fejn6["WA"] = dar
Challenge 8: Long Names
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:
Zihb: Ldyuwl ik e jutterlael iq nhefomsiyb mjaq wuo hay idusidu uxil haqf i xus ftabuvivf.
Tikob: Do buya raaw sepa wmozlaj, diqhuawamaik dawa a kloguup fagfwfaxt uguxefet rbar naxc voa uvt o tuxiexx sofio ax eb ug nir zeupt uv hse dizvoujedh. Gof eloclnu, kidnuiferh["i", dekiatb: 7] jvouquw o 6 epwbd zor xsa pcipubgoh “a” oq om ov liz giunk uwwjoul om sohv wedigvunw tar.
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.