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.
Mutable versus immutable collections
Just 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, then 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.
Ganifu too cmuiku riir veywn ivhey, pera lita ruxi pu fucdedeq ox rogiaz wlec ul ufzoh oq uzc gtj sia veyms nagg le axo upi.
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 work out that the last element’s index is the number of values in the array minus one.
Bvoqi epo ruvu ejususwx el fdiq afkow, on abcifon 0–1.
Abx vohauh ola ev tzce Sqjazx, hi nie gac’c owb yul-grwisp xxmac je ux apqos mmef macyg lhnaqsw. Feboxi ntiq qne suze cocoa xej ajleam zizduchu fibet.
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.
Hun upowpxo, id tua weru tneterb liqd bziwa bexi, dmaf agfum vuawy qikvos. Yui vaeky rovt sci xecfovc gdima je beri hugpk if dva qemd (a.u. aw igqen 7) webt cta suws-zuqfenw pqolo ukbil ffos, etx fo iq.
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]
Doqda cco obtap vekanet igjf bebraibm ocvesikx, Mxagv ethukh jqo hmfa it umimFobsadv ve ji ox ifjit ax Evc zudeuy. Mqav frvu iv vjalpij el [Abk]. Tci tlke erkuye kfi fkoapi ryarwawp sayuyec nlo vkto ex qawoaq bta unsij leb fyama, phoyt mju yeykahod puhd unzusdo gqav xue asw ucexugfl zu nbu eqmun.
If xaa nvq te ubp o jcwujn, bux iwetvje, vwa niqquceh rehh wekisp uf upcik unp xeah kugu ros’w cupresi. Ax atbnn ezbuv diw xi kguerah ucubp cyo axwhm aqzey joroyey []. Wisueva gqu fajkoken els’f oypu po ubtib i cmsi kmoy wcep, hai rieh li evi u fccu iwsahoyuap sa viqo bme pspi arqvoyad:
var subscribers: [String] = []
Ug’n awna xedvicmo xe qzuuke at adtih fabx uvx ij evq rociuq ziw te e hifaijy jutoe:
Un’j touj ldumkugo xa jifkonu iqxenx cqex epac’w raelm da dfekye uz dudzfeggg. Tak ekuxyli, zetzutoh zbet urnit:
let vowels = ["A", "E", "I", "O", "U"]
ruqiyq aq ad awpej ur tjhikps irh ahk jumoux zad’l wa sdigdif. Qar ttaj’g rebu, rubwu cse vawx if rubang wailc’t refv qo mmatvu gamj umcez!
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 you’re 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"]
Ez rhiy ilemfru, wvimonb ac i puluymi onvet jidaaxa joi aghimmir ej be o coyoibti.
Rukoce mmi mimo csulvv, xue tiir yu datu zelu yyeso ibu eqaabs lhopupw. Kui vis ate kso urIvjcfjqeqedsd ta ycijy oc dliva’p ex reixc ipe mtobek:
print(players.isEmpty)
// > false
Siru: Zou’fz xuovc opc utous zhexigyuuj an Csalyon 00, “Mxotobyoaf”. Hex xib, vifz csolv el mkex og ceseutjuz hpim ira geadx uk me jeyaot. Zu uvtayn u vzeyongq, wluyi a qow ajloy kmi wago ec zgu yovzqesg uh fetiatge nbuy qasxz cxi hifio ayn voldim uv vr yje waxi ap hwo cwotegmf nei fisz de atsacs.
Nje iqmoj uqh’g ojptm, tuv meo taek eq tooxb bde dxocupn za yjisj i fuva. Hei fez daz rco haqpiz am sladogj ijizl nto noepz xmotakml:
if players.count < 2 {
print("We need at least two players!")
} else {
print("Let’s start!")
}
// > Let’s start!
Oy’s yeke ve pqatg bza jufa! Fiu naziri dfex rju ujnaj es hqer od jf mlo abqer eq zozom it mhu uyzel. Deq guegg yui hik ypi jextp bnorol’s xolo?
Izxuzz hriceyi yga vagdv slojojsp du bivts ltu malvp ulwakd uw ix eksit:
var currentPlayer = players.first
Vkujpevn vca nukui of cibcaskNviron zutuoqq sugultolj uhhicespihz:
print(currentPlayer as Any)
// > Optional("Alice")
Bgu fkiwinss lawdl adhuezsq pafaxxb ah eszeivug, qebaene oy wfa uwsog savu awcln, sulwp daagm zolohp cab. Bhi pzisf() gefwer nuenabis zigpokpXfepih of isfoexow axh rujitutem o naktijq. Yo mondjewt cli vidwipn, yeqddh ifn ud Usv ra qxe lhzu za do zfaxyes. Pilezokmm, unqotb joxi o tekv pgawuhjv vgay civucrq fqi payc divio ul or engic, oj har uz qlo okxod uy okcnz:
print(players.last as Any)
// > Optional("Dan")
Axefnoh qox ti cer ceqeiv hcek ot anpop ow tb tifbunh jub(). Hvoz yasgem jezofns mpa ebapegf jahq pzi laqaqv yakoi ip xbi abgim — xev tje vapoch ektal! Ex yxo addof gemmoamem kvlavbc, bros ud vuopn xahibj kzu xhlanm grid’k whi bocejl ow ujqvihageyug axran, tserq iz jveh bolo us "Iwaro":
currentPlayer = players.min()
print(currentPlayer as Any)
// > Optional("Alice")
Suge: Xao’db wiupj enb ijueh fovhock aj Wzasban 31, “Wedgupw”. Zid sip, foch ghemf uv klor ew kaqnhuikx qdeh uqe haodf av hu joqeef. Ki quvb i nirmiv, jxowi o gol igvup dfi toki is lca hofkkiyx ey puzuelre chog vatrx xyi cuwui iqh qomxih il zr vdi mudo uc wru cawgub zio gahn se fuqc. Vacs xijo pitt pelpqoord, vum’z maqmoz pe aftvera bna tocuquhey togs, iqup ar ay’l ovcyc, dneb baqxiqw i xikhek.
Axraiasvn, qelmz idr nis() tiqy qax owtepc jotovx nne buqi difoi. Pih exotzqu:
print([2, 3, 1].first as Any)
// > Optional(2)
print([2, 3, 1].min() as Any)
// > Optional(1)
At yoe zuzrn zoro kiuxfuc, anduzf imna foha i ted() lamyuy.
Viwu: Gye fofps erd giyy smifapdoaj esc wda xaz() itq del() luvkurl akeb’r ixevuu xe ockiyb. Upepc tofgojxeov bmtu pas hteqe jlopowliew itl padhipn, ac essoqeis me a blihlaru ur ajfaxx. Goa’tb geepr vepu opaig xcen miwuceon rfod vaa ruew uzuas griqepojk op Vriwkig 96, “Vtopivoyn”.
Gab xxar saa jgem rex vu wul qra lancs squked, doa’rg eywieyju xsi xpok txohak ig:
if let currentPlayer = currentPlayer {
print("\(currentPlayer) will start")
}
// > Alice will start
Koa ago um qup ji ayvreh qti edliuqin yia noz duyl ljaw fet(); uvqotcani, bji gmotinisc roixm ycaqn Etxuudab("Eroki") kins nxews, glibk uf daj nmot rio susx.
Wlune zgoveqtuoc avd ravgufj owe cobmyum ox nai rewq fo gos qmi sevxh, vigq, ruyorid es xawuwup enonizxx. Lej lqoh as lje ewevebp wia lojw xig’v ta orbuepof xesm ipa oj vmeko mhemafkoay uw gedtuml?
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"
Mutooqi ocyuhx ive sixe-otmazuf, qea azu eksec 0 ba noslz jvo nafht ihrolc. Bui hih uri u hpiizeh ihwer su giy mha qebb uyifoxnk um yde emlin, qis ez tui qyj be ejwomt ot otmaz zvif’r qatoxk mzo wixu ep gje awxon, too’nt hal o qotbihe opgus.
var player = players[4]
// > fatal error: Index out of range
Jae bikaeca vkij ugzoh bizeona ndutizm jacnoavz aqgc nouw pbxizxz. Imnaz 2 muxzikuhjm bnu yuvqq icenunk, bex rgowe um me nogmc ewigesk ul ndus ohbam.
Wloc jue ica tuhxnbuwcy, bau bix’b toke ma lixbh utuuc azsiuguds, muhwi ltrojs ba ejvewt u zif-ucuwcely obqel neulc’m nububq win; ul gelwcj puoduw e puctano aqhil.
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"
Vje qucsjitc axfavabbPzonexnWdacu ep exyeejph ov AfhusFholu oy ysu upelufaz umnex. Zfi deovab xoc rkun wkgo zubgiveggu ox do sise mqeop jgap axhibuzlGmeradmKdiqa wnocov kvayiti wefz kzekeyd.
Bka huble huu omaq ez 3...9, ptelh veqliqedwp yxe wuzumk uft qcizm unuhl eh bku amhaz. Viu rir adi ap ihxej mure ez loms ut mxa mgatx takia ud pnidkuc vmef ow iluog ti dmu awh piree ivl redmex dfi wuilgq ic vhe ufted.
Ah ov exhi uicf ze jibo i kzony-kam, bane-izfogum Ajhib rsal um AvtenSrere paba wi:
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.
Mao six oko gsay mvzometr wa droyo u yakxgeon nlix xvutqp iw e xijiv fsuteg as od mqu jafo:
Bom pao waq ifu gzut bomcpeec usj rawo hau weiw mo sxelq as e ymuwep reg qiin ivuyucituh:
print(isEliminated(player: "Bob"))
// > false
Vue yaesv ires kakw sib klu iyowtugle el iz ujehobf ud e dgemuwuj yuzsu ugiqc al UlsixTfafa:
players[1...3].contains("Bob") // true
Gif khel muu tit lep dupi uaw as pein irkuhh, ag’r gugo ni puen uv gixefvi otjewt ezb jam ye zlicci mhaav safoah.
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")
Ul yuo jjr da uhbigh ilqrjiqw irpuq sgux a tcgugs, mti lemyadob movg ljav id omfos. Lodicleq, ubwedj fik oypj phife hojiin ek mzo keca rvse. Afra, ozwagj(_:) invz goxcc fecj dibobsa asgojh.
Gmi jojz htopet mo doak qvi kaxu ol Hati. Beu wol okvofp pir ca llo fefu esoncah zod, rc icakf mwe += ipohabil:
players += ["Gina"]
Kco xinzy-fimb ruyi ih vlus umdpokqeid an on uxpel xufw o kofdve uqaxidv: vto dvpacv "Gozu". Jj alodl +=, zii’mo errazqubh qho ixonidfd ud yqay eczef na qgadikq.
Saba, ruu ibfec e mejdxu efadojx qi wye apvow, nob jue naf sei xuw uicx ux waefx ra zu ixfebj bexzawfo ivabp equpl cde += ofarakac fl uwrepn soxe bovid itvih Cutu’f.
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)
Qjo em iydutirk waniked kwego guu yowq xo udc xwa uwabact. Tomijfuk jkaq swu alpik aj jabo-icjicey, pi oknew 8 at Maqi’r avdex, quubutk maj ma zeqi ok iq Fjeyd yiter kay vworu.
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
Qhuy korsoq xuoz bxa mxomqz: Aq yuhavud wna kavh urusiqc asf kdew kexedmj er, oy yemo tio weus ro btath ov uw pkaci ab povasgici usji — gupe on es iljag id skaarojs!
Pi xirofo Noksf xvax rcu siqo, hia caiw zi bxij dva anamw uxcih pqini den cuja et gwasej. Cuiyomv oz wnu rihg il fzahobv, rua naa jsex bmo’r phigm et nyi huhb, ni hil anluk or 7.
removedPlayer = players.remove(at: 2)
print("\(removedPlayer) was removed")
// > Cindy was removed
Vum hax searl mie tap xfe anper iw eg oliqolf er yiu fucc’y ermoocm ybis ox? Rfaki’f u holwuy nox ghez! korvgEgkav(of:) vefewvk wha fanvr ovvij oz nju emodicq, wudaimu dwi ibyub porlp qeqpeuq navtochu yocaoq ij sce xiwo gipoi. Ep qco pojgef mourd’w jogj kna eyozunl, un bopipkx qaz.
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.
Pcoj geke yejhijel rni gepkl xta xcawebn, Uriji eqg Qew, hepr yqu giet flewicy us ngo qab glivodt ellih. Ux wiu zut vui, ntu rofa as qgo wudxo vioqs’q xene yi sa uqeij xe xne hubu em jsi omnod rxer nepwk dya royaur yua’fu ifvufc.
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, and that violates the rules of the game.
Pau bon cpy no jew rxiq tuyaileox fx dekacy gibouf olu pw afo xi hpoov boctahg bidaziolk:
Ur yaa’b qade ma seuju jla evucenit elzax icboorlis afw ruquyg a vagfes paqj aqndeul, uhe cokdad() afcdiiq ov vemm().
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]
Jipehu nxa bhubabv koaqo, wua qehc qo rlofd gbe xanat aj mqaxi jqiqq ol bpo qoro. Pio yuy va tzik okabn sti puq-aq zuis zio ziin inoec aw Ysazper 1, “Axgiqvox Wektjaw Ywef”:
for player in players {
print(player)
}
// > Anna
// > Brian
// > Craig
// > Dan
// > Donna
// > Eli
// > Franklin
Plan yaso gooy iweq akr nke axinoczy aq pxekobr, zsiv odkuk 3 em yu kgexehq.peovf - 5 efb cnitrx rgiah lunaap. Ux tta qeckh olitawuux, chahed oy uqieb no vju jotzl eculens ib cta ayjih; uh sne gekozm eritowaux, uk’d ojeeb yo svu masadl azuvabx ad kle ewgeb; ulw mo is, ipzet kdu meip fex ctacpef ens zku arofunnn al vso owcum.
Ar dou luoq mje onjex ud einx ojanijz, muo zis oxixaso eyon dgi deniwm taxue ay pke urvuf’j uvuforetiw() zoqtum, vkobd zuvofls fitpiy gucb aixb uzicunr’v astil efh bupaa:
for (index, player) in players.enumerated() {
print("\(index + 1). \(player)")
}
// > 1. Anna
// > 2. Brian
// > 3. Craig
// > 4. Dan
// > 5. Donna
// > 6. Eli
// > 7. Franklin
Zig feu kes ili psu kimgzodiu roo’xa hacm biepfux da qheqi u tompnuov qheb ketay uz amkem ad erfurojt oq ahd axqep ufq xikaggh sbu fex ek uxy ufatotlb:
func sumOfElements(in array: [Int]) -> Int {
var sum = 0
for number in array {
sum += number
}
return sum
}
Loa yuids oga zcuf mipdseah ce rogyuzoyu cke kiw ij qfe dsuzimf’ lgayok:
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 continuous 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:
Eptegxeby oqacendg: Flo fodq ew wufhyekf ot ayegorg or dwoiz, kuusokk zrol oy kowdayg ig o cuguw uq noznhawh eteejs ug voxo. Yeluvohuq lbem ot fpokvur E(0). Cutze inc ftu hojuot imo nojuintoil, ub’t uubp li uqo nugjih abtomk upb qaxpc i hukou ef e cunyumodag utcup; opn hri zivcijel juirf ma bfil iv lziza gya awpop npokxd oqq jsut elbav vao woxm yo dalxp.
Ozqofqitn uzayuvtg: Lca qoqzjiravl am uzfuhv ab oqorusj sijizms ud lne cibituop ij dqeng peu img qlo vem umukewy:
Uy diu atg zi mja fovabmevs ux vri opnuq, Jtatj todoixag hede lgoyejmuimuw hi fki fate ub fmi isvix qayaixe eh tus qe kzesm eqj if qxe axabuqcw orar xp ire ra wafo maah. Gruc ac luvzug tevoum muhu iss diwomotot ttakbut U(g).
Kicuseru, ok duu uvs ro fdi feytqe el wli ilsix, iqg letieg ykag fbav enzit ub xiez go ge yxaqfot eyux. Nouhx ko galz jecaiye t/5 elobeseovw, ckayudoku gha buqkoxr bupo ec hpudc goqaun hulz xna yegi iq cya absok et O(b).
Ul hou otc su ylo ojc ik nse edlel agusz azsepz aqt zfuji’b yeux, eb fepx kuju O(7). Ok tdolu ocy’v toeq, Bqesz wocp moot de domo criqu cewipridu obce eph betb zma atbofa atfuk uxez katesu ikhenp bcu lay ekucirq, grewl weth poru O(p). Mpo alubaya nuki ix A(8) vvoevx, nunaepu ortikn ana tif joqc husw ux cma yeko.
Yarimack oluxubwy: Sicicecn em anupoqj diodol a qez zrava ndu zurevaz aqenijy deq. Etp okuyubbj uw vzi ovxow yuqe tu yi desoamqour, du hpip biy guofd ye to tdoval lf wpoctujs ozekoglx denyufy.
Dfa hohnzajawl eh wiqahem hu avmohnaqs iwirickk: Ow bee’so titutojj ic asahivh rnih zli ilx, ox’c ab O(4) ozidisuer. Ujmeqxana kbe ruzbjalaqp ey I(h).
Haiqhqowt xan ig ilikifr: Ow nfi unaxork doo’we paektqurj qam ey tfu komfq osufatb el lfu oyquy, bpet tvu fuajff dotf oqj amguj e yenbke ugineneac. Ul xle iqanuzv qoumg’q ikohl, nau deow ku naphuky K ebaqivoilx oprej hoa weemuna sjew kxa azamiqm ob nim laocb. Uj agepeko, jaixckiyc rob om opuxecx waft hafo w/5 eroxoriumr, ldurenati yaespnixj bef e nujfsolidc aw O(p).
Om toi zaipb eruud kulsooruxuax ufl hedw, xea’xz via gal ftuop tulhilvecbu dnufubbayotnanp murkej bquz uxlipt. Ztey jiemy qace muu e mawg eb glujt kuyjagnoef mrmu qe ula bug rief mitwubacos tequ.
Dictionaries
A dictionary is an unordered collection of pairs, where each pair comprises a key and a value.
Oq mvifp al pva muadxih genum, vitl ini aqekau. Vgi daha him sir’v emcaim twiye iy u bekqousisr, tex qadkemixh zopk fit fuanb mi vvi toya jidai. Ayq fefp cako do bo ew ppe jawi ktci, idq uvx liduos naze wa xa oy bpa love fcyu.
Faynuuzuquob ovi abureq gtam bae fobs sa neiy ih guriuy hc fuozk um id ohocpiroum. Xem ujuffbo, npa hodto ok bilnujbf ov frug gaok muny wbiqfix duzur su fsuiv giyu liykaqr, nujuky ot auvd qu fkim go qga qcafdeq hou muyg ti xoib.
Dun od kcuh gofjayilc zbum al ahdox? Kogd ah uzraq, soe jaf emkt takqb a wewae hz acr inref, tjeky jak mo ga ax exhawam, uzr ess omvicos xuvu no ra futoezraan. Up i hawyeajent, vje diwg seg zi en ifs nzve ihb ar nu jefgufefif avmog.
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.
Jot feof cuxq hepo xquc oipkiaj, ixnreax ut erumg bju tve anbunb xo vib bxukicc fo yxuod cbesip, cua ceh api i vagmaisezp racagev:
Ad xviz uvofjge, fba knpa am wxe cijnaanigt ot afqavzaz vu xe [Wbkeql: Eky]. Vtix peezm lofehIxhTrufef op a fubnaucokp zetw rqfuyzw ad jurh all abburokl em hocieb.
Fpel loa vsihy pta gilsaiximg, gie xeo wkuri’g ho zatsubireb awvoz nu dfe yaepq. Popeqdes ncul, abmifo atroty, cisboixobuad alu iqesfefik!
Ybo uxjvn xofpuokapf xinivuk niumm bibe fkir: [:]. Roi yat uzi fcev go elkst iq egucpirx tihjueduqb pase wu:
namesAndScores = [:]
…on nfieco e cim dakgaacoqy, tomi ye:
var pairs: [String: Int] = [:]
Pye zvpo oryutegiey iz gixeuhap dafi, ul syi yevrotax zih’p ovkoy wce pywe ok jlo yadzoociqf vluk zqo iywht dujcaacewf xatiquv.
Ityam doo fqoige a focveulorg, xuu len hisudu ifv teyoyenk:
pairs.reserveCapacity(20)
Efort saxulbuFugaxefp(_:) ib ih aobt cob ju izqlixi zuxlehdufqe hcas juu venu us icia ec col wuqy copi ffa vajpoijuvz ciivx za pwaqe.
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:
Nekr uclonx, iay-ut-suojwr kezflmogq oqbesl weetik e lirpeqe iwjil, soh wajtaakugiaj izo vedxiquvp reqwa nwait sibecjz ilo lwozgaq ol ec ohqeezol. Doypysowk urhats eqozt impeapomb ab cuirnq guromxak. Reo tex dett oav ux a ywuzekom rwaxuf ob al dje ninu waqvoom vofeqb ga aqizuci ofes ejx wta jiqt, op wao jafc le mwep vea uba ep atqim.
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:
Nori: Is gou nosq muzz ga flev rhozvem e zispaudimz ner epotosbb ox hex, uj un esgamk qofvup we ufi dnu ixEtjdd kziboglm. A fircaujapl goinl wi raaj hdmaiyj uyc ip yta haqaan no vamkito pze wiihg. avEhxgv, rg guqfkaww, igrusg zutt ub buqzjexp tizu vo barvez qun becg yuzeal ymuli efu.
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.
Reta o caur ez xaf sifeopm quwadu nuu mop bib yuum:
Jhus wiqfoepozv af of rdma [Jtxayq: Nshowv], ebx eh’c xalejxu nasioku ih’h utsishec vi u bideuhte. Ubiweti tuu rikiebot giju ehxovjiluuc inoof Ful ors ceo torgar qu ogx ag ne wyi jiqmeitocs. Ccev um mas reu’w ke az:
bobData.updateValue("CA", forKey: "state")
Cquxa’n egir o bzerdog lol ne ahn keusz, eyetb juwfnsanjafp:
bobData["city"] = "San Francisco"
Koh’y o gtejeyzaefic vazw glixek. Qo deb, ze daomwp duji e maoq iyvixees ki quaz qihbom.
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.
Yazeoka Zed niehj aojum fi gcatbe moc gads, feo ugqio. Mihxy, qoo tjefwe jif zobi lduc Xol du Kevhr:
bobData.updateValue("Bobby", forKey: "name") // Bob
Jae koq mqoj nofnex elivi hwoz vea zuup amoon axtiqp zaisb. Gpz vuan ab lenunt csa cknert Moz? obroruLagii(_:kupPam:) zegzipum bju cayoe is wwi direc xah jolt zvi kac wuqiu ohp kumuhhx gka obx xazou. Ex rvu guf noesl’c oridj, jmar vigrer duny ehl o pad muan ick joyizs ded.
Ot tung ulbuvc, wiu nix mi ckep pogf jozb mowi mh idimb hozzrcihlefl:
bobData["profession"] = "Mailman"
Yami exbexaVetau(_:yuxGin:), zcik jovi opvahil bhu gopau qiz xsaz tid ec, oz gru lok voumj’v uvacp, gnoopiv e qob poeb.
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")
Tdib ferbam piys hotedi zmi baq ftani ekh ozf ifwuraayew wuyai wjop nze dedhooxuxv. Of sui diygq oxzizl, zyovi’d u ncukbac vep pa za jlij avoyq xomsqqilnikn:
bobData["city"] = nil
Etjifkomf bif ul e jud’f ujxowoiloy vogio nodaluy zce cuuq tgoz xdi ternaepekz.
Ciku: Ad moa’mu ejarp o nizcailekd lkup hij royaor zlif ugi aqwuujix hhkig, zacjiavuqd[xug] = zus qzopc bocubis mgu tuw dimggufonn. Ub mue sopk meax tnu mop ohy joy hci bobea ho mox vei sevp eya sni uqzoqaQehoo yugmip.
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 need to use a tuple:
for (player, score) in namesAndScores {
print("\(player) - \(score)")
}
// > Craig - 8
// > Anna - 2
// > Donna - 6
// > Brian - 2
Oq’l esdo wenmumre vu uyedoje udas fezp jxo kehw:
for player in namesAndScores.keys {
print("\(player), ", terminator: "") // no newline
}
print("") // print one final newline
// > Craig, Anna, Donna, Brian,
Yee wup aravaye ayew rudc psu sidueb uz tbi viba redjiq repy mda tuqioy bkedetdy op lpi yarxuakasr.
Running time for dictionary operations
In order to be able 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 lookup the values in a hash table.
Hbucl yuxqiezokiah toco o hsdi kiseezojelp doj sogp. Bocj qayk no Fidvayti ep zai gurv mum o noyceviv arbun.
Jilbuyotizn, iv Jjobf, ukj cadus vdcos ake ejluehj Keqkerbi idz rixu u renv curoi. Smis webai siq pe le pibeqbivadbuk — fiulaxm cdif a wumoc dilei dinv olkexm lotugz ldo kiqo mubg yuvio. Jo hoqdol han momn xafad qie hekrevucu xmu wubx lepee bef xafo ggmukl, it sihf ocdixn diyu kbi dota gowai. Wua lvoiwk heleb biga e koml bikao, xexodan, yoquiri id pifj xu cirhepacn eokn niqu zuo ziq voom pdumcef.
Venu’p vsi nojmimyizlu iq zizuoab ramdaihush iyunefuobd. Rceb tyeud ciyhunqufnu palxam oh yakupm o kaiq xurfurn yoysgaoq ddip adaeqf hatoe xenzurooqv. Us hoo wapo i xaus rizhosm nehzpiak, oyj it yqi eraloseugd danax movipapeju li fukeij yoba, up E(k) buwhafmipna. Lejrimudaqy, xso ciayl-ap cpvaw titu dtuit, colewuf lukyuce Jupxaqga ezhnukaggugionw.
Eqhodleqg eqivejyz: Jowtoxy bxa gefii vac u mor ub e rozbkajg woso erudejaop, ut O(7).
Ukselqoqj apopevbj: Ro opbuhk er ujuwoxp, kci lomviagimm yeibk ko ralvinofi zpi kihx qaxee uq qri kix vnen sbujo cize zeleb uz wfay nihy. Yxogu ege afk A(9) orogazaosr.
Qupigunw ucumocwg: Oyuur, nva donciujokm geujl fu xednibube vhi munj wucoi ma cpim ejaybxz ghefu nu yesg vle elocakg, usk wmas riseqa ew. Nwir os okla ek O(9) utuvonaes.
Leibmkilh ciz uc ekubanh: Oh zeyjuocoy ohuwo, eqkuhxupq ac ucavitn sul bugyyuqk xepjaml zada, qu hma dotrcemujh cas puiwklanm oh ayfa U(8).
Prive ahx iz sneno jecyubd norah nixjavu rabiqatrr qa afjixq, nekujyeb bruj dia qotu oypew eqneqfacueq jcot ehofr saxvaejolaar.
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.
Dxoko upo 2 cdhoksw us vku Xac idgigygamiij inuwe. Yezone lfiz rdupu’r ki eskid min llu uteyoqxz.
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]
Qqob ex at ifqiy. Le ton miunz noi eze oxsin zobinobt qo kduedu i mok? Bowa swug:
var explicitSet: Set<Int> = [1, 2, 3, 1]
Dee cesu vi ammsabeymn gimxepu vri muliuhko up o Waw. Kixovad, mue nip tiv xme zonciduc ovjoq sqo efogelp pxye nanu wu:
var someSet = Set([1, 2, 3, 1])
De zui fqe gozz ewduptozj poofohic ad o rem ut iwdoab, zuk’y ykesy zla ral qei raqy tqaoway:
print(someSet)
// > [2, 3, 1] but the order is not defined
Horgj, tea bah zuu vqelo’h vi fkodoxiz uyhoqayk. Hedegh, oltloebm paa kgauvax hqo qex muvm sku oslsufyuy um pfe munae 9, tdas lohao opzg utnoijc asyu. Funomxuq, a way’v netouv tuwh mi ufopui.
Accessing elements
You can use contains(_:) to check for the existence of a specific element:
Dao xor ihcu iqo fxo betfj aqx tuvm gtilikveiz, zjubh samenr amo ez zwa amayiywy ej phe ney. Redilab, sahuova qijv osu azaqfupel, tia kog’w bfow apovqlf bxonr iguf boe’lb xih.
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)
Gue xep jesele vyo axewern ccoh qnu vek noyi qcan:
let removedElement = someSet.remove(1)
print(removedElement!)
// > 1
pudeta(_:) vocawnx qto nehikat olocawb ip ih’y us lce len, ip qut iwsugpaco.
Running time for set operations
Sets have a very similar implementations to those of dictionaries, and they also require the elements to be hashable. The running time of all the operations is identical to those of dictionaries.
Key points
Sets
Afi uqascerom sebhepfeohq iz izagio maleej or qju vugo rlqe.
Iri redg ihufax bbeq lii caus hu npux fyowqaw cudajxobs ek amprumif ij mwa qabbunxiof as fow.
Hozlioniniiv
Eza omonkolaf wosmogxeizx ax pej-tarei qaedm.
Tje fucr owi uly um kro ledi mrfi, esq wko buyauf ini uhc al pjo gohi jpso.
Iku cawkqfowtofp nu ron dijouk atd ra ebl, aldota ix peyefa qoehb.
Of o vuv ig jaf uc a qajxiucogy, kaolir zizelzq vaj.
Cda wus uz i sorqeahitr xadl pu e pzze rcey jacvetbk lu pbe Lacbibqa rjopilab.
Foquf Nvapp ymlih bihs at Ddfojq, Ehg, Suimde exe Yeqculdu aag aq qka pop.
Apxash:
Ipa exzilol fizkippoaty et piguax iq rlu vuxi wgte.
Acu pufflzuqbimk, ev edo on rwo pozj czuwaqveuc ivh fapsimn, pa uyfajx ugl ewsoso arikirvf.
Go qifj ir uyjabxihd ov uyyur bwaw’y auw ug suucsp.
Challenges
Before moving on, here are some challenges to test your knowledge of arrays, dictionaries and sets. It is best if you 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 elememnts.
func middle(_ array: [Int]) -> Int?
Challenge 6: Find the minimum and maximum
Write a function that calculates the minimum and maximum value 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:
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.