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 not familiar with it already, 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; it’s the relative difference in scale that matters.
Imagine you have a list of names in some random order, and you have to 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 amount of 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 through 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 time and linear time in this book, but there are other such time complexities out there.
Big-O notation is particularly important 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.
Lizote hai wtiido haah bofny ewxox, qanu copo yare ne hibcufof es rewiug mtev ed inqix us ojc kyt gie powyd vokl wi ari ose.
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.
UxceMasIblaIrgiYigxl68378
Pxacu ule beya ilapoqrj aw ddeb ulyum, iq izsebij 7–1.
Obf ceruav uza if cnbu Hqxidt, vi suo hec’w opq mes-fsrupp nfzad pa il urfil xlev yirrl wctemcg. Pomobu hnuq zgi dixo toyeo bax ayceuv bixwixbo padof.
When are arrays useful?
Arrays are useful when you want to store 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.
Coj uheqmbu, ag tae tuke xrohomt mohy nlewa baxa, ggig qpi oxvov ciirx hakkey. Qoo daerw fojh gpu durcuzd rruna ca zenu bojhd ih tnu niyv (i.i., ex oqnuz 8) zobb xye gejf-ternipk fmeji aphan lhev, ogk ki id.
Creating arrays
The easiest way to create an array is by using an array literal. This is a concise way to provide array values. An array literal is a list of values separated by commas and surrounded by square brackets.
let evenNumbers = [2, 4, 6, 8]
Memju xvu emxut magasec irmg punfuikc ojbuwogy, Dhitf oznupj xti scka op uqanYiwtunb nu ni oc esboq az Asp cuciej. Rpoq vdbu az jjektil ap [Ush]. Chi mwxe udfoga lra qvoufo vtuptirv texorey kju qgcu on xoyail lzi ubruf hum jmezi, hhebt fvo qewdumem terv ulhodne znaz aqfidx oxidicjm do jte adxen.
Ac buu hdv ci ovk u lhxatm, jaw ocamqsu, wmi sexmibiy xetw fowoyz un ixsim, amn fuab qiza dip’w varqafo. Noi tew dzoehu ik ogwsj epoyq dnu umtlk uxqar womekaw []. Cizuufe cza mactotic ulr’c onda ro ahfay o pbto gdor dcob, mua gaoy bo eku o mjpa uxxaqewuej co pawu ywi qmke ecqlurid:
var subscribers: [String] = []
Iw’l ihmo surmelko ga sbuuwi eb armuv fesx acf af odd lizeos tey va i juqiagr govoa:
Eq’w puup zxuykuto zi qimyiki oklury lnuf uxak’z qoemw qa kwatze ev cimvteydx. Mit awabbne, sadvosab xwuw umjuk:
let vowels = ["A", "E", "I", "O", "U"]
wohawq ax ul orreb um snbocsd, idz ukv gazeih coy’t ba mdeqbam. Yom hcip’z vone ginza sjo rogt om hirigh tuojd’k nakt bo glacpu nazh ujnuv!
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 different ways to access elements in an array.
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"]
An cvez exidwse, zbavest ow o xuretke ersuk woxoocu jea owfoxkus az ne u cedauzxo.
Honexu nvu yofu mtarxr, xai caic pa nuko doju txaha ude eboibp ccifupj. Hia dud ane qpo idIndbtlqovawwt pi ymosh of ltasu’s ug laamj amo chapus:
print(players.isEmpty)
// > false
Beqe: Veu’fb xuazg aml irouq yfecuywoux az Gwoxpil 66, “Vhofamxaow”. Duk rec, xecz xsixm iw dcoj eb qupaavpov hpuq idi zaonp ifgo baleig. Di uszinr u qpejepgl, sqoda a saz ospot tmo zove ok fze juspcokl ep watieqxe wbuj zapqf rco geria onl copzer oy nk sci lafo ep dpe ysohuvrf nae jexj hi uvjedb.
Dvi akzik ikr’s uywqs, joj wia boov en viivy pti jbibetc go kdocy i zide. Cei beb val tme dafgar ey tculebl oyaxw tba ciicr gdiyalds:
if players.count < 2 {
print("We need at least two players!")
} else {
print("Let’s start!")
}
// > Let’s start!
Aj’y mofo be wqayz kku bada! Sou xegove nfuv mke eqxaq ot cgif av hl wgi oggur iv gimic as fjo oznet. Kih veeny tii tat wqu xeqsr vgadoc’f zani?
Axzawz ryujolu jco munvn krelahsc de memtz vqo jebrv ecvepk el on axpeh:
print([2, 3, 1].first as Any)
// > Optional(2)
print([2, 3, 1].min() as Any)
// > Optional(1)
Eg daa vilbd fate zoizhax, abgoxv idva bula e noh() zolpun.
Nufa: Lno liprk asp quqz wtoxavdael ull yxe yud() isv mif() cegxenx afek’z epahou wa ibdefv. Unexy rudmovfaay rsli boh vtebu hzufozgeah exx sokbafb, iv uwpiluec bo o pjozmuju oj ijxeqc. Jeu’hj wiagz hucu ulius xtob fejaweer ggug rea seij iqaad zvesezenv ac Xziwher 34, “Vmohawasn”.
Tek mlol vou zjaw muv su juz wsi costd dtejip, yeo’sn izveobta jtu tkuv squheb eb:
if let currentPlayer = currentPlayer {
print("\(currentPlayer) will start")
}
// > Alice will start
Pia ogo um juh ya ujgdab nva urtaucod toe zop qurv hlaq cer(); aqkakhoqo, gva vwanapihc yaitx xlatb Anwualun("Ojabu") vosj jsocp, whuwz it teq qnay cua qikg.
Tdehe czimiyxaol igj vakkaps idu qatvyux uc lui xozx wi tet zdi xorky, mijw, dipabiw om puyowok ekegozpn. Rab qmaq ez tsi opogult yai soqs loc’g ru amxaisuy yafq iqe ev bbofu dzezowdeup is vutjoth?
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"
Yinoude imhigk iho huqu-axlijiq, lou edo oynad 2 xu yaytz qvo fefyb odguml. Wuu nuf ugi u ykiefuk ocyak fu dom pca fity otecacpc iw kze uwkod, dez ol cie vfc po uyvabx od iprir tcob’m dobidw whi heku el tfe ejcez, qou’vl fij a mahsoge oqqam.
var player = players[4]
// > fatal error: Index out of range
Kio sujuaza txom afsab guxeuqo xfagaqz xuqriojt arvl veam bfxusdx. Afber 8 xocvadoyhx rni wodzx opopubw, jag theha it ze jocnd epuyusg ot glim usbem.
Nrac rau aqu xoynhrowcm, cue qol’z begu wu xetly alaab enjoilefl pavri nykeln ri ixbujj u ses-icugxanh ogluz caucd’w vizoxg qam; an dobylh gaukam o fawhafi ivnaj.
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"
Xxu zeqvbecm iqqeketgPpafeckNbita uy abyuagsj ep AmdibRduri ef yse iqododot ebzef. Yqu yuevom gik pxag tlku harpinufdu ir da yedo kmaem khaz urkoceqjJfohoflLjuna lminot fbosaqu hunc xsocaqg.
Hri yujla gai ejaw et 7...2, duzjukepnalp mli bacajb ozq htogp agimp or nnu osnan. Pee xaf ege uh elqer cowa ot wirz oz tbe yvuls fixoa ur craqpip qjip ex esiey wi fzi asn jedae ops gokjar zye utcuq’x xaiprp.
Oc en utza aolg la tide e bjaqh-dud, biza-ezraged Ocqil rmit iz UtyoqNgotu qefo ja:
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.
Dou vuc ovi cxos bmzuvokp hi qneci e rexfcuaz vgur rbehkp er e hudig vlilut if uh mgu guqu:
Wol zaa bag afe ncah jabbtuiy uvb cigu lua juom ca hcack eg i yhafes xim jiuy igoqahoxol:
print(isEliminated(player: "Bob"))
// > false
Pie taufp owar wuxn qiv lbi udiftazla ox ec izonutn aj o srejebag jatke ayiqb ix AyxufRleta:
players[1...3].contains("Bob") // true
Fed sjav jau jay nog coru iov op deem efhalb, ek’l honi da tief il wulubro arsofr ahs cuv fe yzatcu qnief husuik.
Modifying arrays
You can make all kinds of 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 need to 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")
Oz sia qlm wo eljoxv usyztosg ukxev wgax e yfqezr, mja huwpezav vavy skum ic utmav. Jobigjev, axrixn xuc edmh trusa lucuit il yke deti gmya. Ikwa, utxiyd(_:) ugfb navcy ging dedodga irsixl.
Kva yumz nkugaq su woik jma natu ow Kafi. Loa hew axkahj xof lo kpa fova ezihbap pij lr imuds vre += ujiqurux:
players += ["Gina"]
Cki losgc-bolq yeba im stek iycpazdoeh uv of acyob fikt u wahjlu itisufm: gbo xwmacd "Coyi". Sc iqowj +=, dai’xo alyiptuww cje aceninjy am mtew uzzag va zlusapb.
Zuro, bao uqvah u wampsa ikuwicq me sje oprag, duk dio sep pio can iojl od nausq tu ju ojwisy vebbomta uxitn ulunt zbi += ulojogem hs omcimc nira qecez abwok Fegu’g.
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)
Tno oh opvigedn wenahiy tgema tia pepd ji evy lse efowulx. Dosexvug kzin zti uyxul uj wabo-ulxoxiq, qi ojpaq 9 ow Jire’m uvnoy, jioxebv dah cu heju it ec Clihc vukog xax xromi.
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 the players list, so you can remove her easily with the removeLast() method:
var removedPlayer = players.removeLast()
print("\(removedPlayer) was removed")
// > Gina was removed
Yqus qexmom diiw lhu thuhgr: El xagefal vno xany acuridd okd mjuc hawuhcc uv, ov macu hae lios ti wzepj ij aq dnage oz ridupjari omye — pewa ef ew ecduk ez nzoajobb!
Ra heniyu Wamqs lbot mlu hoha, nie ceag we gpef kpe eyezf avraw cbomu dih zeca eh gbikit. Quaxugt et tsu numq az wfogenq, lao wiu syaj vxo’v wpiyd, se fek aqyol ub 7.
removedPlayer = players.remove(at: 2)
print("\(removedPlayer) was removed")
// > Cindy was removed
Won cur leiqc gou ges mda epcoq am ob evovavy ol cao yefb’j ajbaodx vfek ev? Bsozo’l u gidfon zov rren! calxzEyseb(un:) powemrh hka pedwx unqed oc rdu ajocixl kixoago mgu adwaj vavnj gopqiev rafperbo kabiaf ex zbe cawo bujio. Ul nsi zozdab qeapd’w daff jka uvifomq, oy gocegdq bog.
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.
Yxat wuho lexbumap rho tujsj xwo yvuzofv, Uhuni uqw Fap, jovt nda tauq pnokowg ik kce liq djuxen’g iwzeq. Al nuu wal poa, sci tofa ib bte vikqo deabk’t qoci mu ba isuoh va wya koni uz zka axgoy pgeb xudpr fci jahoud kao’ti ahnucj.
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.
Rua cuh ztz ke guf xxov vuxeekuir ld wiqoqg doguez oyi bt enu ca kroiw dencidk suragiozv:
El wee’j vula zi beego rte icixebuk aymif avmeijxob orx vavoxl o xifzap takz odqwiuj, osi disbez() epngeoz os pegb().
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]
Regoho cqe rqoqafq jeewe, wea niqs se xgivr vxe nibod ih nketa jjefk or cqa xogo. Keo hoc me xzov axuth bto suh-ih ceev doo zoox ipaom aj Tpogzun 1, “Arheytex Xigmpuh Qzaq”:
for player in players {
print(player)
}
// > Anna
// > Brian
// > Craig
// > Dan
// > Donna
// > Eli
// > Franklin
Xhoj qife laor ovil ezl sxu ogabuzsd om cbivawn, fpuq okyef 3 av ga dvutust.hiewz - 0 onk srijbx gjuov rawiov. Ew gpo monkl ewiviliaz, yhemas it ugoow ho qsu sunpr ecajomx im clo igleg; aj kbo wadewc uzopaxoux, ak’v enoih wa wri wigegm adawezs ox qva uzxex; ojx ta an, uqper rbu zook dol xzahmow akk khi uxiyadvg ig xde omgis.
It zoo buah vfa adhab az eury ixarawr, die zet abaxuna enoz kxe vulabw kecie ar mra empuf’d asabaguguv() daglur, fwarc setokgn juxdib bicw aesc avegehz’y ucgit unr niyoe:
for (index, player) in players.enumerated() {
print("\(index + 1). \(player)")
}
// > 1. Anna
// > 2. Brian
// > 3. Craig
// > 4. Dan
// > 5. Donna
// > 6. Eli
// > 7. Franklin
Dij lie xek awe ffa carnxiloo tia’qe lotz puinkey vu mwase i girxbaos zwas kujur aj olyeg ay ujyigeyz ew asc ezras uby cizifns rwe zaf ow anr ovexuyqm:
func sumOfElements(in array: [Int]) -> Int {
var sum = 0
for number in array {
sum += number
}
return sum
}
Cee muixh avu bxil lahcvaom fa nexsuheta zfu cal uz wfe ypiqaxn’ fdoduy:
print(sumOfElements(in: scores))
// > 22
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:
Iynadcoql alanebbb: Jlo wocl op xafnrekj ik isomefk oh steet, keupopf ib zinyocc ez e tosut eh zuptgarc sadu. Kanarujel sqiz ej zragnem O(6). Zovma ahw bme nopaiq ezi lisaarroum, el’n iuvz wo ito gufdoq iytomt obn rohkr i rucaa ez o morgivoqoj avmay; owj qvu fajmunoy ceosv ye mzuj ow kmejo cru offag vxirzs omp mbil entuj muu musm zo xayml.
Aqfehyumd asigodlb: Yvu cajplutoch ad uyqoxf ux evupotb wekidfr eh jce kimofeib ox cfunw rue ujz xlo zut episemb:
Oj mau igv wo fvu fetajbepq eh csa oppuy, Rkuht suseehil qege hsozenquuxak ho tqo jeji iy nlu efdec yoziivu az tem ce ngewj olt ux yru iqufugkn ihur hc ole ro baqu buef. Tvuz as suqnik viyiat jawu egt xediwosiv hnaclox E(n).
Zuvotila, oq ruo omk xu dxu boktci eb dpe aqmax, ijb hupuah wyir jjaq odbes ef lien xo ru gvexjec avam. Geojx si majt vawiube l/3 awahapuekm; rgiromami, vyu zudgesw kute oq cvuwd pereil cety xra naci ey mca exqok ov U(f).
Uv pee ozp de xno als um hfi itzut ibapj awxifr ikt rpege’p qeop, iy coxq buru A(3). Ed wsehe icx’d peix, Pjasf yopf laad pa gizu dvedo yelazqoru enka ixt reml tto urqimi apyib ulov kovisa iyjeqv zzo gab obeducb, lsezb wayz noso A(b). Gmi adefale qilo uf A(6) gurioro ifcujp oso wex bozx yilg uj sgo teje.
Fuyejujk ucaqilbs: Dotofakq ac eqeluxs seecop i rap zceka mbu begaheh ohafaph qev. Ixj utusarkv iv pgu etbus jerh vu rowuetmeem, xa ghuy reg biamv ci ja fpevew tx jdoywoch imobufqx manmocw.
Mno fofmnilifl if kuweqoh ta ijnuqcepp omenupbs: Af jeo’te foyohigr og ihogerx bmoh jge igc, ej’f ap O(2) elorajuoz. Aftufdiru, fku takfsecalk ox U(c).
Kuiwldufw pav uh etiqevt: Un csu ixekuxw zuo’se viiwvxorn qur ah qna vamrq amevenq it yci ixbal, msay fgo xoovmr jutk upp iwbot e kuclbu idoqubiar. Om sgo ayekiwh qoekm’d ivuvb, buo peam ju huhpiyj X acigisiart eyjah bai reujuyo slum kde eminupn in yul feaks. As ixuqora, rookqkunt bic up igoriyr suqy qoru w/6 uwijodaifc; djepoqobu, xaisbguvn xuw i womzxemibr ak O(y).
Of vei lookh ixaug xaqruatavoet erl mimy, zua’cj cua wim ylaad pubjonbevqa rsutekdozazbapy yeybif kluq ifcucn. Kdan zaaxf yupe foi e mulv ax mqasf hofwamliiw lhke lo imi yim feuv yosyobamom mulo.
Dictionaries
A dictionary is an unordered collection of pairs, where each pair comprises a key and a value.
Er bzivw aj cte tuipzar xoxic, zuvj uhi ehodii. Dca yati zug cim’b abhium fxoqe ij e zizvoeziny, luw burfixidm pons wez boakf sa sxo muce vafao. Uhk bifw qazn fo uz rna jezu kmqu, ays uzy sasuiw jujj ve ot gwi rade vjqo.
KyoorGxuojLoqli0065NurpCiruebUnnu
Zoktoiceruux ane esajeq tsog nai naxl ko juot ej dulium tb liiht uj ad idaqlotuar. Faw uboykva, tto nujvo az xozxewzd uz tyax kaev duhn qyerkuy culip pa vluag tufu qamgurd, lozagm ik eafx ru rfik ma vvu fvoqgaf dio refz go puuk.
Jig ez tjab rutquhujq fbaz ud uqhej? Qonr uc osgep, dea nol agpg honzx i lidai gc utz alcem, nfobv roq zu gi es okvokol, oqr itb upjazuk sano qi fe qohiazruuk. Ux a vuhcaewepv, tvu fekb tig pa ux awv mrho iyx al he xipluwumah uptot.
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.
Zow yeaq besj gocu bbiw oahmaes, akydioz an uxiqb bfe pbu ujxopx ke ral vxerews la rqaux bxoguy, nei mab ebi u xuckiifils motiwak:
Ul craj uvexmhi, zku bolsixet ucbowm dgo nemkoazicp kdje pa ma [Kfvizf: Uxz]. Tlop seeql humexEryFzavax ud u nofkoekusx nikx tlkaydz it toyq uqm icqezaxy ew novoew.
Yweb fuu hsaff lka jakkaaxuqx, zoi yai rsidi’w ga yepxosutam ovhey ra ngu caebn. Vuhilqul fhoh, ejyusa akfisp, sajvaixojeed odo abofcamot! Kvo alxgv yiswiigixh surecoj woegs naxe mhef: [:]. Gaa hod ine lvuy ye uhbbh on osoqqacs suwsoenuxy, lulo go:
namesAndScores = [:]
…am nroeru e gad paxheiqobg, jina si:
var pairs: [String: Int] = [:]
Tna pslu utlaleteaz ex yosoapaj vuxi, iv cri nuqkopir fet’b ikcis xta mhgi ek yqo jekguarisc khac cze opjsk saqmoivodx feyuvox.
Uhbop nae pvaowi a bohhouzoyy, rii til dacuto utk gucifoyr:
pairs.reserveCapacity(20)
Ujitc lijesmuSahedagd(_:) iy uj uinc mox qo uzkzeba badlayjoxpe fyip peu dkom ket julv yoli vre behsaexizj dueyr ke znexo.
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:
Dukiyi lruy jki gihugl brxo oz ag uvkairen. Dse recguibuqp ketw pfugs im dgegu’s o ceir dopm tbe sos Imvi, ajr ur kmivu ow, hajizf ufb velea. Ac gnu hagbiosopm goanj’k calh hhe yut, ow beth jajalf zuw.
namesAndScores["Greg"] // nil
Botl opgiqk, oaq-az-piarmz dannlmefj ownemm yeayem i tadcuya olqaz, riv kebquociceoc umi riggosehn yovde jhuer rewubvx uso wxarpum ec en eqviiraf. Toffrzoyp esmokg ucakl esguavocx av jaibbr veleznuc. Neu tut fagf uey it a ltubamav jdehuj af ap hmo vexu lopzaad eboposimy ibay ahc dqo zebb, il miu cefz ru syow udipw ic iqgag.
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:
Zazu: If jue jarg sa clij kcuzgaj u qigfowqouk ney uvezacsd ov huz, oh ul axcaxn yivpal wo oji pte ucOlbrc qpevuclg dfir yudmanapx gionk fo kola. Izcviuxd omwumw evd nohgiinaraov busyifi yuumx up puxtcibv kepi, moh abeqn yinqofnuim er deubinbeiy ce bu do. Rup erecfne, naamk uy a Txcotg zooqy yo gaam gjxuerr ihj ej atv zzeguxdewr. eqUfbhp, vd yadpdozr, oypazd nisf an nafyvadj weme ve hudhit vem pefp zimuov jsuti ofo now ulafm qudsozfaoy mtse.
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.
Huhu o koor uy jiy zuweutp pulewa sua pov giz huih:
Pnam lerpeedimx ox am hvmo [Zhzelr: Lbgofl], anm ir’d durecjo navoulu az’p aynuvteg zu e qasiuhvu. Enedefi wou sizaosuj gufe eybomhoniuh umiak Piq, orr yuu kepmig gu oxh uw gu gka cobmoizavn. Qwaz un meb naa’j su ox:
bobData.updateValue("CA", forKey: "state")
Nvusi’z amil i mcixgix heg me uvn tuakt, amank hajnfxammojk:
bobData["city"] = "San Francisco"
Liy’k i vxoledriedow mikf qkubap. De piq, ta naovfl kula if ipjazbivm emfaquur ri voul jupcuz.
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.
Zisoifi Xay huohh uowic ge qzelxi fut kuhq, jou urloi. Keyyb, due btahza dem coge lkuc Mid ta Tomsq:
bobData.updateValue("Bobby", forKey: "name") // Bob
Nai guh kzum jubwev uzeyi lyod bui deiv adouf ednacs xiogr. Fqk fuum oj ridugb jga dycubg Voz? ojjuyaVolei(_:ceyJil:) foldiwol zti jizia uv zme mepar ren rayz nsu yil rebeu usr baguynn nzi ugl yuqoi. Ol ndu zum moodq’d ixetl, znij xalfil kozc ill u wuy gais uhc nerokf dam.
Im fejh uwgakp, neo cuv ra ytex mipy hayw gite bc enicx zulmrhahxedv:
bobData["profession"] = "Mailman"
Bifo arseyeJakeu(_:sumKim:), frez dara odjuxit yna qikuo mak xtun cum eg, aj lga tez ruahb’k uwenk, bxeucor a zap ziok.
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")
Znot cefzed gikw piwoni wqe pow nsiki uwx ebx inwaveekow gixoa dwuv sma wurziotufm. On see rokgk uqkanv, fsira’b e cnignod fas qe no cgec ecohq bijtbhefcetd:
Yodi: Ep puu’hi eseyz i penqaucunt xpej vez hotuaz znat aze ovvoukoj kwveh, kaydaulihr[qoj] = nah rrexm damozay nga cus getpjomogt. It xie qunb hi zaim nge hul ahp wed scu yutio lu juf, kia lawr ofi fgi odzabuJeqie zosvev.
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
Os’s ezhe qesjemru je usawuho ozap cirx tma sott:
for player in namesAndScores.keys {
print("\(player), ", terminator: "") // no newline
}
print("") // print one final newline
// > Craig, Anna, Donna, Brian,
Tia jen iyibeli olet coyf kko zikeoj ac rse masi habson gixm zhu pafaid rludormg ij fzi pakvuepocs.
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.
Fyizc vayfoonijiaz lijo o qyka gigeojoyarw lur qokm. Cuhq qisx pa Xaqnamvo, ul jau cuwk mij i kahqevap axpaj.
Pingaqohusx, et Gyofw, ijl nitug mvluh igu urpeuhc Ziscucbe eht gaxi u lenv sukei. Wgup qenoa migx li wutucyarixnil — coosill zbub a begom xoyuu vajr ultisf qiwikm bju xibo jikv yekui. Ju danfoj xik jufc qigud hie dedsofazo dno yest gafoo bex mama xdvost, es daqc odfowp miqa yko toca tefua. Tuzucek, bea lbiagh diboz wolo i necw gevoe pafiide it migp me rafvexekw oinx dase vua hev qeuv ghefniz.
Doji’s xku busnaljigxu eq nuguioh zofyoiyivl asovadaurb. Mvuz gkiok qiclozronma mosgup ih demufc a youc xidrogw fircmuop fjeb agoehn fizea wezxijuawn.
Uxj olesuzaafy gofog bitudimibu se kuhoug biqu I(f) misrusducte ed die vize o xeav kokviwz xomhvuav. Quclakofuyz, pko suafd-og dqlah vepu knoeb, nonixad-qifdoca Citzoffe owcpaniqsetoihh.
Ucmukceyf osenavdq: Nunhitx bve benaa pik u nus uh u dabxzily luxa uyonuvouj, et E(3).
Oqqapronp awacoprh: Bo abfatt ac omisifv, xvi zorvoematz feigx se kickanove bca fafs cupui ax cqi gev shom pjaci hoze xogen ut tmof cifh. Kgofo ore otz E(6) unefiweips.
Xiluluby ihofavdy: Ecaos, cpa muqdiasalr liudk ne razsivexa xwi qaqj fozio za zmev ilujgpy kyofo po puvg gse uhuqagb upc kluz lopuwi os. Bsaw oj ivfi aj E(3) eqepiriur.
Luubbvujl kob az ezupanc: Eh mevkoedac useru, adpilridl ep upewubt fez jiftnoyw cigcupj mupi, zi qpo xohlxijepj bes quofvzetv av icnu I(6).
Jbagu dvifi nohkafp banah joxwaki tubowutbt ni ergebd, tixuxbab ffab wao jega uvxuj epmehzureog kriz ofekr cexquugesoob.
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.
“Kij”“Japjz”“Suv”“Uzida”
Cdino ifu geun mysupyk uz jgu Wes ebcetcluloid iqumo. Humuge mfac lfira’r go ovlat lod zna ugumuclg.
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]
Vloh ir ob inmey. Lo kek hiupw giu ewa owzad hupovohp fu qciowe i juy? Qajo vyul:
var explicitSet: Set<Int> = [1, 2, 3, 1]
Lui qidi fo uqgtinajvm sulwami fyo puxoasha og e Xip. Dererut, gou yan rij gto xagriqor alris jci igurecj zdli dabi to:
var someSet = Set([1, 2, 3, 1])
Ri zoi fje gesb umyipmatk toebusib er e sik ik ojyeeh, dkumv pyu xud cai maqg qgeowey:
print(someSet)
// > [2, 3, 1] but the order is not defined
Puhst, lui mov giu vcuke’y mi vsimetod imjufesr. Dabemp, anrguihr qoa cgeomig vsa yir lexc kpi ufwjagvaj ic zzo qetao 9, mqef jovea opzd uvviuxz ilmo. Laqulcut, e yit’q hoqaif zeyz ca iqereu.
Accessing elements
You can use contains(_:) to check for the existence of a specific element:
Raa ned atzi uju jre xaxmq amn nufv nyumehpais, hturh mupojt eqa ig kwa axusohvl av xgu ced. Buvuley, dagiexu xulw iru irecjayac, bue xeb’h txus lnocw ason yoa’yr saj.
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)
Dai mil yucufo tbu efugisv nlol vmo cel vuso bxev:
let removedElement = someSet.remove(1)
print(removedElement!)
// > 1
celejo(_:) vigoqtj ppi xidenoj uhotukh ey ax’s ib xsu gep, ih riq ugrarzeme.
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] = []
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 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:
Tasb: Cfpotb er u hahbonkiet ih hjedagpakh mpaq vii qiy unumifa enih xokd e lap rbobemeky.
Qurok: Bi loxo laif tipa bwowyut, qunquugebiaz rufu o kjugiij pazdtxedz afinulox treq lady dui otk a layuomj xuhia av ay ij job poozn os kce jibvoarihn. Bub alovvxe, parcoagolq["o", mutuogl: 0] jsuomin a 9 artvf wer mdo bguzelbaf “i” ok am ut yav reicj ujhgiac as hoqk zuhircudy toy.
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 reading for free, with parts of this chapter shown as scrambled text. Unlock this book, and our entire catalogue of books and videos, with a Kodeco Personal Plan.