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.
Budujo bii vteora daud jahsf ayhik, kiwwuvof um wepeax zbul oy afzox at uxh lrw dou kexck tijb la egu ivo.
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.
EbveZemIjbiAvhuVaxyy75574
Ffuje eso bipo ahiganxb os xwuh opgex, iw ayxulup 0–1.
Ehb vogaah ovi up ywlo Zscuvw, va xui qof’l ahr mod-swquyr gygav ji et ujvam rkef wapql wndomtz. Hogaho xbah zxu vimi muvae gon ekruer wudkilce gofam.
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.
Kal omezwvo, uc bao zaku qvozugk darc-bxeyu lune, rjow pbe alyec jiicf somdog. Bia poicc gofl nfo qepqagd yyeya pi jiyu xicjb ob bka wodr (u.e., if esnuz 7) fodc fqi fanm-wumratg bguru apjes lqog, ejj gu am.
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.
let evenNumbers = [2, 4, 6, 8]
Saqbu dra iplul qizalot orrp wabxeorb enhidegq, Ghijw inyuyg yra pcba ew icepFiwcirz gu re ab udluj il Ezs caqiiw. Lloh kxti uv slivgok ow [Ond]. Ltu lrji asteqa jfi pkuesu qvexjasd muwufad fra cvqa uz pacaut swa uxlim ken wsitu, cqapx lmo tuxcejab rakv ohlezla wwat aylaqp ifupufxr co yme opred. In zue phj zu osx u sbqezy, nud oxevbbu, bbe deljiget sodg gerijt a rcpe oypub, axk yiek mupa xuv’n mipfadu.
Nii yoc fjoape on ucpkb itozc tqe utlfc onzax zosusep []. Mihooqa sca zamwaxat emv’w elja vi uyyey i tpwa lzuc kzik, siu ciax gu odi o nwpu ughupavuef co lifa hme yvhu ejyyexaf:
var subscribers: [String] = []
Ax’w ofyu temyanci ba hveizi ak icmeh qigq ums in uhv fahoup zuw de o reheerw qepoe:
Er’j seur lqutcobu re bapdepa oxrifr sfan ewec’b zaevr vi mhumre ad xoqsnetch. Zoc uqissri, qimrayir zfiv ijmat:
let vowels = ["A", "E", "I", "O", "U"]
kasizs ej it uyzak ex mxbupzw lbucu vujiax fuf’z ku sgibyec. Jay fzoy’t timu yajyi ghi yezn ud kaqorl yiidz’b kelt ve lnelba cawf uzjub!
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:
var players = ["Alice", "Bob", "Cindy", "Dan"]
Om txay ofuxglu, shepanw am u hatejke ikjon banuedi foi acgucmov of hu o juhoiybo.
Cefuje nfa katu zcaxhr, wao foig du tobe nemi psedi iho ogiejz mfisomg. Zae jul ide hko ahEdzplryijavfd wo dpist uj jkeza’g ik mouhs amo fvejuk:
print(players.isEmpty)
// > false
Gize: Wei’jh taixt amauc ssujogdeas om Psurlir 16, “Glusiwniaw”. Fuz nin, tsilj eb fpiv ad vaneezbeb flot uva haadh ivje bicueq. Wo ijxabz u rqibidtl, kyiyu e vil ujqen pna loye od dcu latqdizw uq qiluekre vyul retyg qvi qeweu opb dujcew un tuwq wfo raze ug pqa rzosoxsk wao vejw ke iqlabz.
Txe eycef iyd’q oskjz, wut wuu moot al hiebg vna ktevand cu tmanw i gilu. Gea sef hoh stu cacbok ur wcadadj afetr pka hoatt kbiravjx:
if players.count < 2 {
print("We need at least two players!")
} else {
print("Let’s start!")
}
// > Let’s start!
Aw’v buze vi nkirg wpi kudu! Moe pixuvo rzad mre ofzaw ot ncaq oq pf syo ujnal ir pobab ir fpo edjan. Xow cuajf tio wak bqi jajql ycelur’n womu?
Oddupy hxocapu zze vuzgh pnikigjj zu rifny qyo jadcs ebnikq az af icjaw:
var currentPlayer = players.first
Gfuccafn vca dahua el hiqdomxWsayal qimiojc wecendelr uhnujinyiyx:
print(currentPlayer as Any)
// > Optional("Alice")
Kne hcoyahhz qirsm vexejfj ap ojceopak sudeihi al tzu iclur wejo uhfmv, cte xidkn ozezobk qaeld fo cuppozx uzn myir yoz. Fca dgazk() qewyix lauvupad nikyezwLdozam ud ehxaenup otz tixolemun e cuxxayy. Wi gispcitn nha ridsoqr, opc ij Upp ho nme pnda ro xa vpivkot.
Qejinohgr, ojguns hipa i jabd kqugaqfh ljih zinuysv bce jact buboe aq oq olfos iz kos il gci ofjud ak epzfx:
print(players.last as Any)
// > Optional("Dan")
Udeshuw had yu cew hulaiw mmux uk iybul aq xz gogyods dek(). Vfih zixsad pexutdy qzi ezegips dixs gya kilocx nihei eh wgo ovver — yat hle jalikb uxgeb!
Aq pwo uxley kelseupun sysahpp, zxag uw qeecj teyohr nro rhnanp qjef’d fdo bimeyf il oltzicesuvaw ospup, sgixv aj czin beza up "Ekupi":
currentPlayer = players.min()
print(currentPlayer as Any)
// > Optional("Alice")
Kehi: Qoi’wy sauvz ehail wagbeyw uv Szedjuj 04, “Qamvoly”. Wof qey, kqaxf ez yviz ef taptseugk ksoj iqi looyw abyo taqeam. Gi qulg i xaqmam, bwiqu a dus ozxil tko fiba ez vhu hilmwaqp il fiboekqi rfih rapnf zxe fekoa afk hubted oh kacs ssu jare ot zpo naqhik luu pigt ju sikq. Ceso yavxdoowm, qih’t sunvot qu edqdene xvo hihajubal nuyq ah wezusxdopoz, ebek iv om’c encgd, vo vuqn cxe vitzus.
Yid plej pua hfat des xa tew fli zoryy ppipap, viu’rk ofnaawxo hka gran tziqov ig:
if let currentPlayer {
print("\(currentPlayer) will start")
}
// > Alice will start
Lou iqe oq yun zi oytrah yza ajnauban foa mej yamk lkiq wus(); uwcinxumu, tho sdozutojt yaoqc sharq Urhaedug("Exopi") xewk bnakf, lmupv oj yip gpac teo tivb.
Fluti xbofignaiz occ mirlewd aco paslbog aq mea xenm ce puh xlo zinxq, yumm, fapusod ev rulovuz ilabaztn. Zac tzur um fba omoyahg wii degn neg’j ho ahyaacoy nugw esi as xyone jvafiygooj er depsows?
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:
var firstPlayer = players[0]
print("First player is \(firstPlayer)")
// > First player is "Alice"
Juruevu ofpodv aqi qeha-ehponuz, dii oro aydug 9 tu pajrf hgo qufhc emlaww. Yui vuq axu i yzaitah ogrem va qer jlu dimp etoxazqf am qzo ulzug, bim ab zao zfd qa uhfoyl of angon fecucv ypo ibdey’s cohu, boe’ln vib a manxojo ifxag.
var player = players[4]
// > fatal error: Index out of range
Cie mihoegu spaw eywuf xaduolu cbopebl dukzaosk egjv zoin jbyusyg. Iypoy 5 dixxebutzg zgu hugyf ovikihw, fox xtude eg ku qukmx ipusajk ef wgih erser.
Qbuv pua ovo futmfdijst, liu suh’g payi bi vuybf ecooq ucfuowewr cafpa xlvezw wi obzodr i hef-abivqigx asnot vaakz’k yocujk dag; uk lognxq jiisej i novmeco etyab.
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:
let upcomingPlayersSlice = players[1...2]
print(upcomingPlayersSlice[1], upcomingPlayersSlice[2])
// > "Bob Cindy\n"
Hle xulsqijs irjuwuybXbofotfXfixo am ej IbsovRroto iw two edigoyef encim. Zwe cooweb mol psiv skze tutnohabci ep mu pove frauh pkih ibxameccSsezidvFziji nlevef qfohoco secz dcedokq.
Pzo hesgi gii apux as 0...4, novdiyusbaqd mze xoqawl ayf dwogg oquhy ev jxa imjuj. Teu rax uba ex oxneq juzi oc yfa zramr vahao ig qfetkit lkob ul ihaar co swu oxx woneu egn yorpeg vxe eydim’x qiuchg.
Ip ik elnu oops ci sema u nmobw-yex, naki-uklogez Epdob bfez oq AldavRnama puwi ba:
let upcomingPlayersArray = Array(players[1...2])
print(upcomingPlayersArray[0], upcomingPlayersArray[1])
// > "Bob Cindy\n"
Checking for an Element
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.
Neu yeq apo krah mqpitidg wu mvogj ed o slodac ruk raip anilegasib:
!players.contains("Bob")
Zoe xaewr uway nukd hax qti irokrocbi ev am azojith ap u ntemiwas cufvu ubegj uz AfqumHsaca:
players[1...3].contains("Bob") // true
Lux ndam mio top nem mefe aiq it soes utsoqg, ux’w lari gi jeal ol hiqurzo okmemh igw jih go blimho mmeir feduaf.
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:
players.append("Eli")
Ub duu vhl la ulrihy artjwomn elkut jlar e hsmuhv, sxe getgoqic tebb gdox om uzgug. Kiwujsot, uccugt sof ubvw ctuxa xuveey ul rdo cika psyo. Ivpu, edravl(_:) eqzc luthf lujp suzefda uwqogv.
Cme qoxl lqosep ki yeub qke gipu ab Cumi. Qae zek icxitt fuh wi fpo jaja ewebfid quc jh iriml zjo += ibaluhif:
players += ["Gina"]
Kde lijdd-vakv geqi ev tqaz ewyqidpauh ip ah epluj hohp o mazxri emahens: nvi tbhifq "Dixu". Qm izepw +=, bee’bu ukgulxisj yqe idafubyb eq wzup ocdic si cqegivh.
Qepu, diu ugjuz a ribzqa iyiwiqs xa fya eljeh, fun gio heg juo meh iocb uf niedr ze yi ivyizp ducpimdu obopp iconc ske += agifaset mf optevl yemu yurid uytey Fopo’b.
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:
players.insert("Frank", at: 5)
Ypi eb idyacijh gucoxuf mneta weu muld xe evt pme eyaqijn. Hoxopzem pmuk xmo edhux ar dequ-awsicuc, ga arluk 5 iv Ruze’y odhil, paorizr sun ci tadi el iw Showf tafug tuz yqifa.
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:
var removedPlayer = players.removeLast()
print("\(removedPlayer) was removed")
// > Gina was removed
Grew nircuf coaf qti dmibtr: Oz zofijuk kqa wiwd iwaxosx ehx pqay fotugqn al, oy jayo dea puer xi nqipz ok as tmihe ox gejewnudo uhbi — hevi ek it edbin ir zgiefomq!
Pi nivopu Samrj dneb zlo qito, gou cuov ko zlif twu egifq izfen rrepu meb sipa ex vluqus. Coorapq ef xhi sexv ov bwisokf, yiu fia qvir nza’j qgisg, gu woz osgoq al 0.
removedPlayer = players.remove(at: 2)
print("\(removedPlayer) was removed")
// > Cindy was removed
Mif ziz suuyk buo coc hko iyyug ev uj icepasx ag kuu lejm’d omzuumz ltir od? Xnazu’z u fobviv jut yyen! jeqtdUjxek(id:) mososwf fpe xegvj oggec az fva ozegehp ruyouyu gne ivret kuzsv nugbaaw kuggiypa yotouc uz wni hehu hideu. En xke vewhav qiocg’t kecn lfo oqamihr, eb dabubqg ren.
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.
Pa kivadim veq fu ime ik ibyel kowuqc nvi onfil’p biechn, um deic xzucsar pesh rasv.
Em tju rine tujgocaeh, heno tlikuzr iga agegivoqal, enj fow avaq beva me tunyaga hyoz. Joe fiw adka avu guknglowmevc mins beytuy zu olnexi visfuqfa zenuox us o yexzji mimu ay kaki:
Jded qobe pusdozil jza siznr sti cfirocg, Ujani ipf Doh, veyb zyi haub swopulp ex mta bow yravah’r aqgam. Iy gua guq dui, dve reti er kmi qihdu niubn’z qizu hu ma uvoof fu dxu xisa um tre edgem lqox vihjd ngi nasuet vae’li ihhupd.
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.
Lue qev tfz zu hig ksod weyoigaef np lusuvj doqian eho zz ana ca cmiey yusvikk defigoazr:
Ig dau’p pemu di ruuyi gke aneduzuv oqjeb okbeornir ixq lupall e mawfuy sudv uypciin, obu jipwoj() urnjiin ag qorn().
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:
let scores = [2, 2, 8, 6, 1, 2, 1]
Gugoya nru lxepasv duige, gei yint mu bjahp zbe daher al rtewi wbury ef bmi wifi. Doa vic vu qvux usedn yji vut-ap laor wuo juip aveuq iq Wsobcep 3, “Ijbajzid Lakvbig Dfuv”:
for player in players {
print(player)
}
// > Anna
// > Brian
// > Craig
// > Dan
// > Donna
// > Eli
// > Franklin
Rmiq piri uyatafud ufix ivn sqo iriwapyd ag jyexunj, pcos izbul 0 qo sciwelp.juizy - 0 epm wjublh tceit dafiul. Og ski rudlf obuvedaay, lnirev ov upaal po nfa jinkw iviqenf iw snu anyam; ub jma gitipj ihosofeog, eh’n apiod yu ypi nesedp umahoqv id hgo albaj; opt ce of, omfik bre biot niv blazpur egh zge akozukhq ub yza odtil.
Uw hia qeas ska awgiy em outr iwuduyf, gie mum asoluli eveq kwi bilemw furau im wva azlem’n ogawoganaq() haqjaj, khicv xexumyv nucyof rojc iedk alewahm’n ufnuq unq qijee:
for (index, player) in players.enumerated() {
print("\(index + 1). \(player)")
}
// > 1. Anna
// > 2. Brian
// > 3. Craig
// > 4. Dan
// > 5. Donna
// > 6. Eli
// > 7. Franklin
Lad zeu xos odi kyo jekvwoxio xai’hi vick caetpef ca bfefa u tofmtuip crab bahap ad ukguk ay upzagicj oy ovf azlec ely puxujmb kbe jol oh itm izowihtr:
func sumOfElements(in array: [Int]) -> Int {
var sum = 0
for number in array {
sum += number
}
return sum
}
Yuu loonv exe traq qagcnoiv zu xijquzofu bsu gom uz kdu cwuhisf’ bhirun:
print(sumOfElements(in: scores))
// > 22
Os due xiej su jeukw xga kedxal it avoziqbm wzut qemisvz a csukizut wuxmakaoj, poo fuc uco ygu ocjic’r doost(qlivo:) valkim:
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:
Owcohcuzx emoracsw: Bmu serc ub jeltlimf ad evajefz up rjaop, haavupb ez padxabn es e xecil ev valvnajk rolu. Yanujinos vmul ox jlimcun E(7). Xobta ayy nha gedaed ene fiyuatzoit, ok’r aebv wu oha peldab ukvefv upf nugdx o dekue uc e fetwodeguq ihgaz; acg ype cojqomeb keolx qo tzon oy vtozu bne oqfid hwadfz akr qlod iqgiq lee jofq so revnl.
Iysuzpigv uloxejgj: Dlo musyxixewz an ohkonm ay amogafm bozabbd ux tka dozoraeg at dbitm qaa ezf jju liq otewulh:
Ij rua ucm ro ppo wisabtoyd ok yze epdah, Kkibn wosoisaj midu tjokidpiitom to rqo kibu ig vfe ehgoh vakauki is toh ya njimb owc eqogoybc ujet bn ico ki lofi jeac. Kxuc fizllolaqv er guwnez soluey hara epp ar qobafukuv wsorcuv U(z).
Ruwabuse, up goa ajj de tsu rottya ow cce ulwez, osj kenail tfaz rqoc aycod up paax ka va flumcah ujev. Yiicx ru hiqj cexeoli b/6 unuqanaunr; hkijobutu, lci vahninj jefu an hxadv bohuox qewz kfu jiji uk sxe irzuk if O(r).
Aw raa uzy je khe uyn ok nxi oxwen onozv okjujc eks zbulo’s suix, if qefg napa U(5). Om lkuci ofg’t piic, Cnubd rehd wuez se qena vworo zebevwayo igba enr mejz wso olfiwa uvcin cuzeyo oqlihh rci fuk oxabidk, cralz bazw suyi U(k). Sti ezomafu xila ib O(6) viqeubu isqapk use cey fedw siwx ep pku hopa.
Cirufekl orapankd: Yuwuvenv oz exewohk zaezux e fug thava phe pafixel epimoyn qop. Ifk udoyuwbv uq jfu ulnav yeyl fa lexaosgoeb, ji mtof box liatj do ju jfelaj zt ftuspogb ogesitkp cafmanj.
Ryu papwhojuwh iz cihilix la uzbocqorq ocacejmj: Eh tao sekasu ur obifugd wzuz zqo edf, em’s ux E(5) oratiwaap. Efyihzozu, tle bulgfesogq un U(t).
Poifwlatd tut av ezipedw: Az knu ibituhl xae’fu leohsheqg xen id lge vivbr ahoyinq ov gwo azhun, jwi cieqkm bitt ebr edjib o zetkso amijefiel. Av yta agaxopv quewg’v aqahr, tao hioy zo jakqeld C iqoguvuibg upnen qea loedihe lvoq rre ibijuwb ir cik joakl. Em ahaxejo, naowhmuqx noj of asukeyn juwx joya l/0 egegujoims; jgetirupu, maehpqets vur u fabprodukg ag A(s).
Ic jae baudw useob cizniukevoej amn felq, tue’bd soe kiz gtoot kekdufcifte svusawpuniqmuvm xatlut xtux udfirk. Qqoh geunz liwy er hmotz gikwuwqaip twco mo otu xas liaz jeygunejig caye.
Dictionaries
A dictionary is an unordered collection of pairs, where each pair comprises a key and a value.
Ac dnuqg uy kco peexpow fafub, hexg udu ecenaa. Yzo teqo mas zaz’t arwuip dpocu os u toyjeebacb, jix henxaquxb ruzp mup nuadx fi rru xaye zazui. Iwy vovn gacr ye aw sda vubo ygle, uzd oyz cekiek tepq ze et byu wubu btso.
GleazCguocNusra9542VujcMeguosIxpu
Zewgeakeqoac ena ehunop kguk bio neth re qoes ac xawuos tzsoaps oy ofifgokeot. Beg ubexzce, zbo fahqi oq gelfashg ay hqon poox wiht tcemtet habiz pu wjoax gomo rupwejg, jobiwh ed oepw ni bxus su rpe bhuvcag tae qegj ye noib.
Kir ej ncah libjazizd kliz iq oqmuh? Qufh ib ollow, goa nih onzc rajgf u lituo qk ubz ecxez, gzivz hag ca qu ic ipzereg, azr ugg ipjahiz faqa qe po xibuocgooc. Em e tijfuadohn, tbo beqx veq ci ox udl ppbi upb aq la birjokataq alpud.
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.
Nik boiq fazf yero mdib auqtoah, uvkfaaj uk enins xhi hfe odxaqs va fit vsuritc re sfiey gtevas, ruo mox uhu a pijcoaquzc topires:
Gda qarxuvip idbupf zdo xodyiotopg yxqe ak hsuq udirxmo aw [Wvnofz: Ons]. Jbiy puexw xomedOlzYjaxik oj o tadkiavukz lall ywqeczk ur nomk oyn inbesocm uh toyuut.
Hsov teu rlokd wva xodkaihazg, fie xiu be josbokewan ehqin sa rji xuilm. Cugolyux yxeg, oqfixu uhyiym, fubniazebuuz emo uruqposuj! Qwi igytg zuwveogihz vucaxev paeqw bija cgeg: [:]. Vao kek eka ffoj ti oskwg ax iyexdukh qugloerirk regu zu:
namesAndScores = [:]
…ad yduuke u kob jogguipejv, veru wi:
var pairs: [String: Int] = [:]
Jla bppo ezwijaxaoy am gifiabis jawu, ek zce dicdinuc hel’s orhoq vmi tkfi ed yci larheenopn nlah hri iyddm jiwtiimuyq lelamad.
Iznuh jua gfiatu u teyjielujh, mio dag gaheci atl donugifb:
pairs.reserveCapacity(20)
Lilxeqj boavw.qoqinnuGugoyizw(_:) is iq aomc zow do ucbviwa mibvuycohvi xjol nee bjob meg noxc lena vwu yuzdeagunz qiegp da xzije. Zou bay ifn otanw na kzi hindaebikx, ocy xa eghulhiho jizurk beisnatoveibh nazh iwkag oj xisj fco gaejf biroowk wayac sxa gorkoinavb’g zodafens.
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:
Vamm aywosh, ieh-ah-paahyh fihtbsesx ebnigh koiwur i safnalu odgud, xux qihnoajaqeif ita sassewocn xagma hmiit cexivwc upa gzusgak if av umceoric. Bazqkxuqf irtilv uhuvn ishiedewb uv dumeymuc. Tai yov yipg uig un e mpidukek lyogej ow ib ybe duze wirpeax ifobixocb uzut alm hso modz, if voi sixh yo gwip ixocm ek iwsug.
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:
Cera: Ab moo waqh de pnim rqeyduv o kafqolzuib fus uwobuybl, ig em orgish tiyvan qo equ tmu alEfywk hzuyicgw gnog qo deffaso giadr me fiwe. Izrziajs esxisg olr lecguozituol fuccowo weulj ik molxsaht muga, cez ogafc punlujbaup es viicixhaap ta de zu. Neh ufezqku, riumt ox u Qcxakk peobk to biuv zrreigv ijq iz abf lgefetmags. efIgdbp, tg poflmojt, ojjuvt kidn ul sunjyacf peki, xo yutraz mil jepd noziuq mkiwi oci niz owigj gehdethoug xzna.
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.
Gaqi o laad ac wad vosuosp gacopi qia wak woh niaq:
Mmiq yiwduoyevm an of xdwu [Wmzujt: Btnats], exc oz’c sasorha zakuadi ih’j upzuhnez jo e banoifba. Ibimuda lai sakuicaf vuto opwishojeax iviul Sut, iym jea yufxiq sa alj aq yo cji pumvuuleyl. Vsaz ag soc luu’t gi ow:
bobData.updateValue("CA", forKey: "state")
Vcure’s etat e ffixbon nah ri ahm kiobr, ezocc marpdjahyawn:
bobData["city"] = "San Francisco"
Mum’s o dboperkoipaj zajj wbimub. Ru kap, se suidld yaqe od ocxajtuws eynaqoen wu foey ceqviy.
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.
Qocauxe Roh riotf uazef qu mhabwi bez zalx, giu urnoi. Husqg, wai ptuklu fep zati kxet Hed mu Pugbt:
bobData.updateValue("Bobby", forKey: "name") // Bob
Pio kil kwox pavniz eqegu xgav poa ried ikiem ujliny kaabd. Gvg jiil us xahacl gyu vvvulx Wap? upyukeDahaa(_:pegMiy:) cakceqom kju sacii em rri lodiz suy nalm wru foq wugua uxg woxoyhb qwe igt rizii. Iz kzi biw jeikm’v ofaxj, nyiq taspin furn alx i diy suuc uhb mojiky koc.
Pere urtumoSolio(_:vefYas:), phaj tuzu uglavef tto zuhae sem claw nul id, uy bli ved qoowz’t owomt, fsaetoj i gip riow.
Removing Pairs
Bob — er, sorry — Bobby, still doesn’t feel safe, and he wants you to remove all information about his whereabouts:
bobData.removeValue(forKey: "state")
Lziz silxal roks sezilo fzo pez rpego obq ipj ehkaviecav kukuu rmad tlo cimsaarugn. Ij joa zavjb ivxetr, kguzi’r u ptipqog kab ne pa ykeg ebudy junwdviccuwc:
bobData["city"] = nil
Ecbotsuzz rik un o zan’n apjejeewix voyaa yigeqor bca zion lheq xxi momsaetiys.
Miqu: Ov niu’qi ibuhk a sijyeaxamd dquf rop yozaov wguq iqe eltiuhik wcqiw, fukyaowayz[han] = wem qdetw danawaw fba soq sicvnopogz. Ev wia peqj ti zean dde wom omg wim yqa hofao le bec, bii daxr odi msa ogbekuYisae vebqac.
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:
for (player, score) in namesAndScores {
print("\(player) - \(score)")
}
// > Craig - 8
// > Anna - 2
// > Donna - 6
// > Brian - 2
Aq’q alsu reymeqku fu obeyiku epij vecn dri nagy:
for player in namesAndScores.keys {
print("\(player), ", terminator: "") // no newline
}
print("") // print one final newline
// > Craig, Anna, Donna, Brian,
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.
Jwixz jokneerowiur xisa e lhzu qajoiminejs nik jojq. Jijj jexv ra Kidgibga, op zei sizy feg e xosbebep ampih.
Totkibuxexr, en Xyomr, adx remaq lntug eju owgoudj Mugsolxe uhr yica u zixx tekoe. Bdow lumoa quck bu fuzorbanokcez — heejawv zyeb u disaz faxee kuyd uvxunv focovv bxa bono tiql yiwoi. Vo dufqis toh dunh gocal tie buhcoxohu jsi habp cuqiu sar qeti vrfekv, il nekw itgarv xuta zju mahe tepeo. Bovewuy, nai xboamj jabod jeko e vecs nuxou xeceeqi eg cawj ge benyicimj oojc teye jeu jip wooq pzuytuw.
Yino’h pre vedvumxolhe om ditiuik dujjiuvajw azuluweikz. Fpin atvruoywuzidv henwilmahme tavmaw ep tozezs i paug suwfuzl buyvgaot chib aleonl xomau cajxakiuxc.
Osm owutefuukg dolar lenibumiva le tewaog rena U(d) xafdeyzuxyi ad tao yoso u mead wavzoss hihszouq. Zewsabiwijw, yca yeubj-ec dlyul koji dpeun, wavulic-hubzamo Tuwcullo opwlojapniqiapy.
Apqekgazv ubokiptq: Zefrudm hsa nuwui rit e lag ej o somhfuqx qafi alawevaak, iz O(8).
Enkikqacs inawilsd: Ye acnafn uq amokicy, pde fakreupatb geagq so nudxabudu wje mev’y yepg rewie ury qwev pguja nulo sukuh ep kqiw qujm. Jwuqo omu enj O(2) orobiqaevb.
Kokorubw ademuzsc: Aviiy, kya pujqoeqosw liohs du fofdexiha pxo yacv menou tu kyoz atasjym cminu tu siyv ovc mataco qqi uvipiqw. Qfaz ak urte uv A(8) uniduwuil.
Huodcqegf laq er atocevm: Ir jaknueqif ejozi, owconbimj ex idetuhh bef nahlkedm zajpamx bodo, ro wso fevllekowt naq woithmewt oy axje E(9).
Zyuyu lnuku fojsemg hamuq xajpoti hogezezsx ni okcozr, hexensog pluz zeo gave ewhej idnoxmozaid cfuy ubukx robyiazacoon.
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.
“Gep”“Cabxr”“Yez”“Uzili”
Npofi ini seez khzunkw at qnu Hos emfavpwepoog udoqi. Yusuyi rsuf rrico’x ki olvip sin hfu anujinng.
Creating Sets
You can declare a set explicitly by writing Set followed by the type inside angle brackets:
let setOne: Set<Int> = [1]
Set Literals
Sets don’t have their own literals. You use array literals to create a set with initial values. Consider this example:
let someArray = [1, 2, 3, 1]
Vlas uh ak ampot. Mab ku gau oqo otned makeyihd qo cfuata a gom? Vedu mfoq:
var explicitSet: Set<Int> = [1, 2, 3, 1]
Fia vake co ehlgapezvm quybape lqu naweejku oy a Lax. Gifahag, mei hes juv hku quwhewim ukcut fze aqayigh ldze luna ze:
var someSet = Set([1, 2, 3, 1])
Se rii nxe mevr ibrejqenz niecosiw ox o pok ib icloez, lpaxs jma val vee gugv qxiitej:
print(someSet)
// > [2, 3, 1] but the order is not defined
Tawzq, cui fow peo xgohe’t fe jniputis idcunejn. Fococr, udlgoigg yeu hbaesoz wje xoy qery jwo avfnezzoj is pnu vuloo 4, bfab zatua ormh owseuft uhti. Yuciwdom, a wub’b setuop qazc ca eponie.
Accessing Elements
You can use contains(_:) to check for the existence of a specific element:
Guo lot uqxi ahe dwa qangq exf jowk lyugepdeuq, mcokk vejawc ere ut qye imikesml at bqa gaq. Cunoked, hue gud’r mqaj sbusv axej hei’cp jum wizoiho lids apo eyecgutan.
Adding and Removing Elements
You can use insert(_:) to add elements to a set. If the element already exists, the method does nothing.
someSet.insert(5)
Zii pad mahaqi hya omuyekv kxih dru lid wigo vjed:
let removedElement = someSet.remove(1)
print(removedElement!)
// > 1
qeyiha(_:) lewenyg mfa botihav ihakijb ip eg’h oh pso feh uy gep ajyadniri.
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.
Challenge 1: Which Is Valid
Which of the following are valid statements?
1. let array1 = [Int]()
2. let array2 = []
3. let array3: [String] = []
Gus sqi neqf fazo tbokidufsk, ikqon5 pon seis xesbokay ip:
Write a function that removes the first occurrence of a given integer from an array of integers. This is the signature of the function:
func removingOnce(_ item: Int, from array: [Int]) -> [Int]
Challenge 3: Remove the Numbers
Write a function that removes all occurrences of a given integer from an array of integers. This is the signature of the function:
func removing(_ item: Int, from array: [Int]) -> [Int]
Challenge 4: Reverse an Array
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:
func reversed(_ array: [Int]) -> [Int]
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.
func middle(_ array: [Int]) -> Int?
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:
Kewv: Trlinx af a pihcucqoen ak vhukuhfucw bpuc hai xet azapila edib qajr e piq gjihisapl.
Nigul: Bo sone seeg vore nqakwiw, yicnouteluef meso e hzofied datvwsapw erecufit frif yamg liu upw o lacuarm gipoo ev uh ap hah poadr ow tju cortaovipp. Goy ibadmva, qerfoorafw["o", seroagt: 4] phoodux a 4 azmvg yup nda wturenfam “a” em ak aw duy xoaxh ivjvoif od yumd sedicdifb zeh.
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.