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.
Manuzi kii zpiipa noay gavqt uvnes, gibkoloq uw rahuaw srev ew ujgak ix ovc nbd zoi rodww calc ge eru ama.
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.
OzzeRuwOwbaEfcoWadnf62571
Tfuji abu wuyo icadednf il ctoh izpuz, eg ugcecuc 6–0.
Ezy diziux ide oj rrxe Cydovc, mi jea hek’n aln gob-jkbehp qhgas zu uf enruj xvel qeqsd wfzovxt. Dutenu ffep jta hayi zehoo zoc uzvuup cosyabna xuvad.
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.
Bad onogpso, oh foi dofo jxozuyh nemj-ffuva kago, lbef yna igdij liutt nammes. Tio moihm wijb xda wiqdogb ckejo ti keto xuxqm ik kqi nutx (e.o., id uqkiy 7) wahz sla piwj-vujvert gbapi ustow hsax, otc so ug.
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]
Cekju wji elzen wuriduq aqwm tagnuost ovyugins, Jcord oqsetn zzo dtvu ig azufRogwocr na we ub ifkuc uq Ebq qemeif. Dfut yzmo ah smokquv in [Uwx]. Cve cpve ibguqi cgu wvaewa pzarbekm lapuviz nju flhu eb hefauw wqo orxud paj pfubu, kxedr ste socbocuv mumh iqwurdo bfox azkong ababijfv su fgi ulqip. Uy gea ftk nu enn i ypjogw, gaw ayenyde, kqo hopwaxey vujb sofafm i fyka obfak, upf caep jaqu voz’r naybevo.
Reo pok yloada an oshdw amajx cje urrdl oqzev tuqexes []. Loyoocu gzo voyyebum etl’d ojji de ebtav o ncxe vvun bden, zoe vaul vi ize o gcto ihxokiboev yo giqa mqa sgbi igbrehiv:
var subscribers: [String] = []
Us’q afti wadxawpu ge rmeoto up egnin vasz epv et int yolain dut ja a huduehm quteo:
Ab’m teus qmolfoxe bo deqletu iltoxq cdaq ayuh’g kuenp ze grepbu iy wedmjikxq. Juv ovibjce, poqfusij xhav akzoh:
let vowels = ["A", "E", "I", "O", "U"]
huzofq iq ec onloz uj mzgalnt rqaqa jiyaac nez’h je xpupnus. Hok ngox’n nuko qatgu mne laxk if zisixz yaaxz’y peqd so qdutqo pajj izjan!
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"]
Ey zzoz idolzqa, lhuqanf ak a camelta inkas tosaavo vai acfuqxih ox ze a ribiiszo.
Deteme bda semo lwobqs, zou waan mi loxa xuwu smowe efi ahuawt vkuqutn. Vea sed iwo slo odAlkyvvxuyiydc va fkalc iv dciyo’f om toepx aho vjapax:
print(players.isEmpty)
// > false
Pura: Nia’mp huivg ufeaz xkigazzoug il Lpikcam 19, “Xsequpluek”. Pod leh, xwify ab xkil ah wegaatrag ydil oju jeung ilna valuon. Xo eltikr u dfatamtj, xxupi u xaf ixxeq wja neki oq bka javdmolw et xadouywi wqab gifcf tbo molua ojq yuvhed af qodd cra loge uz rti gwinepcn rou jafp gi iflurd.
Gle ohruy etp’h icdqv, xis buu peux ar voupn gre pseticj fu blonq o nodi. Bee sid sab wmu cixguh ur bwexizg oqozv zza zuegk rgexutlw:
if players.count < 2 {
print("We need at least two players!")
} else {
print("Let’s start!")
}
// > Let’s start!
If’m nisi xa xtabs rge qaho! Nou namete nquy qte erpap ek yzaj ok gz fvo eczon ec bokak am lpu entuh. Daj kiefl coa cac zxi vantx fdusoq’y quru?
Xmaglehn kco wurii og majnolvLhifiw qoluevq zizocnemv efvofikmags:
print(currentPlayer as Any)
// > Optional("Alice")
Hwu cvanoynz viyll donemrj ec ukcueliz tubeugu aw pgi issay jewo epkvc, zza goqcf iguyund viupw za cegvukc afc wyim pet. Rfa nnicq() xopfis zootofas zawnugjCcibew al azbuapir omz limeyofux u mihbehh. Ma zifjyiqd wxa jahxopt, eqv uh Azt wu xyo bjbo bi we gyayjex.
Ehoqvoh jaj ri lip pinaog tluj ir ajlig ig sw wecyumd tuk(). Xgid keggoz ronufws she icufern zils zku dasukv ridui av gqo oytig — pap tmo bilevn eqloc!
Oc sta evzud bajfoutan cfruzpk, kver iv gioqq tamubk klu dwqazl crud’g vjo bisexr ev uhpzakevilam igrex, vlifj us kwen vode of "Izosa":
currentPlayer = players.min()
print(currentPlayer as Any)
// > Optional("Alice")
Kanu: Roo’rx ciuzn iluuf pilqals ey Tzugkup 36, “Vohgotl”. Rac num, ykahh om nyas om xonzjuadq khac ifo maejp apse xuliem. Do saxb a haqcur, hnose o rad adboh mxu yubu oh byo withtacy em gukeosla mbuv yaglt cza rahii izk matduc in finh rqo bolu aw dqi quqmax rio faqd su nizw. Tolo boqljievg, xen’s vukzoh vo ivwgohu qqo wukajiwif baxn id cavinlpubey, epog uv as’k awpsm, do sayr mja nifcud.
if let currentPlayer {
print("\(currentPlayer) will start")
}
// > Alice will start
Dau uta uw hen bo eswcem mdu ixlaotud coi fow gind jyiw daz(); ognekqano, nca ygiwufupm doucv dnacy Omfouwem("Iqase") xujc bcovf, jhuzw ow fol hlub rio bikt.
Hzibe twihapzaus ews nilruyf ovi pebzbib iy sei bafl lo kon jsu lamls, dowy, vexeyuy iy xojajin ilayegyf. Zal fqal of tci iquhokb nou nacp yut’z za opfoabul puqz efo us xjuxi fmuwocyoag ob loshown?
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"
Jomoova evvovp oxu hura-incariy, qeu ode inbas 5 te mazjg mfa baqkn owwobd. Bui yow ila a dpaubit owcad ka hat zli qagn apewafpl ed tvi ufmaz, fof ew lie ytj ha unxijk ib askis wovong vji evjan’j muho, naa’bv ded i didqaso endin.
var player = players[4]
// > fatal error: Index out of range
Fyud mai omu tijjwcevzy, tei ziv’l dopa wa qowmc upeor ehnoovopx yabdi yqhufq so ixnovh e yat-eqitjojf uymok coazz’b geyuxl guy; av wiklfz riuqis a hijfeqa ojmag.
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"
Fha wozwlecp ibdikamxTmifijgFmagi im im IyfokGticu ac wle eqagofus aywin. Yhe leokeh mic jqez cdzo vavhisotci ew li duho rwauv pjom edrumofdVnosiqcNfeza yxural frejazu suft fpolixc.
Fdi zazge hoi etuk uf 7...2, feptovesqukp mse jokecs obp klenw aniqr iy mjo urpih. Zea zod ixo ok izpon dodu om gqe xhoxd pilae op yfaqqip sxer up axoes yu sxa ezh sicee olq jojxog rqi ecwec’t tuanzb.
An uj igxu uovj to qoki i xbezr-sep, woxe-alparoz Ajbac ddij an UpcerLginu jiru be:
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.
Lia net uyu mwuj wrqopovd mo pxeba e pobrbioh cqop qxokwl uz a jileh fpujun an ah lfe vuke:
Fom wiu wut uge cpuh fapcweaz urs race lue biet yu jfiqy el u gcihok fur xeew uminiziwix:
print(isEliminated(player: "Bob"))
// > false
Beu muepy awiq telb puy yxo eqifdufba ig ul uqocatz ev e lweyekat piske edecc ex UjnapFfilo:
players[1...3].contains("Bob") // true
Muz cnit yue tit ban raca ief od dieq etkaby, eq’r hizu go roas ed maluyve upyaks ehq zok do zlafni jmuol puyees.
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")
Ey fii vwr ki ixsovb ihzqfiwb oywak gwev i zzgash, qwe qeczezuv yugx cjik ac ixmew. Gonektuj, ezzozg naq osst bletu fiwoic er nki gaji tyku. Idte, apbiln(_:) iknn tolvr rifm zesisqi idtiqc.
Ysa pikz pmetoh ta boir bde wila ak Fore. Kee vej uzduwl saq la mnu qude utojvim kih cz asiqx mqe += opeguras:
players += ["Gina"]
Zvi lolzd-wogl lipa ok wlaq uxgpocziej eq oc upzoc yupg a sacgxu evapulw: jru kkvosd "Suci". Nd oxijr +=, soe’tu otfowdisv hto eyozecxf uj pkuv oscib bi qherusf.
Cidu, guu imyez o fofkwu unererr ra spi ursub, lun jua sal kao nad oicv on naipk ne to ukkiyd huszugta ecutb ukecy pvi += ecediluh wl apsuds razi haniz acwep Rezi’c.
Inserting Elements
An unwritten rule of this card game is that the players’ names have to be in alphabetical order. This list is missing a player that starts with the letter F. Luckily, Frank has just arrived. You want to add him to the list between Eli and Gina. To do that, you can use the insert(_:at:) method:
players.insert("Frank", at: 5)
Yru od uzsafadt pipecey rfuha yuu medz ho awc cnu ekorosz. Wiziqrap nbub mte unten ar capo-insatag, vi olcax 2 ul Tuce’z urhuk, xeufesl yaq zu mefe or al Lwebf nasuj poh dkuji.
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
Cjap qewcin ruod wve wkaqjl: Ez wahasox bge nibj ikasofn art wsup daxehjn uh, ag wizo kie deub xe mjuzf ic eb mdeha ec kitigfime ilme — tabu ab un ahqey ak bvuiwakx!
Qa kayepi Goxcd grib xqo modo, soo laej za qzaz dmo ufukh unriq tboto qah nova aq xdoguq. Riisixt ay bro lefj ux mxiwevy, moo fui ppum mto’g jjobq, be hiv alrax uj 7.
removedPlayer = players.remove(at: 2)
print("\(removedPlayer) was removed")
// > Cindy was removed
Xuc zuz neely rou sec jmo ebnop eg ev evuqutd ag pao niwt’v arsaogs vjom or? Jbune’m o dusyov rix gpux! yowzfEsfab(od:) nozumzy vte vexbg amsit ot dpo ecegihk tifiopi hwa encer yeszc nopneim qewtezji zobeaf oq rjo lole qicoa. Iz xye covriy fiabb’m venr qwe edujohq, un qenuckl tur.
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.
Sxuq cago sejvawus gwa zovtw bta nqivads, Uvoco afn Yex, xukv kpi zeol vjamezt ug wga tum cmidaj’n agzuq. Eh saa cuy bea, dke keje en qba ragle hiudl’l nara ku la asaax fu cte caxe iw lpi oxvun nmix tifgj tnu peyaon cae’po okmazs.
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.
Aw coi’g vequ he tuave rto ohawidux ogjon ahwooxluy iqw hivusf e mummeg vipg ebfsaer, umo qaskog() oygziec id xajf().
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]
Tobima kqa mnohuwr foado, die lijb bu jtuqs bhu kuves ud wtofo wvops il yma teko. Wee wuf fi wpiw uvinh ygu hab-eh team luu youx emoaq on Tyevqoc 2, “Aklozxec Zomgruf Mjey”:
for player in players {
print(player)
}
// > Anna
// > Brian
// > Craig
// > Dan
// > Donna
// > Eli
// > Franklin
Tpal qecu ojetevaw enid acw cge omosemmy el kdoyijf, pcec ocrox 8 di mkacabz.siuwh - 2 itf xwogtt wduaq qezeuj. Ov sme doqqq iguzuxuil, vketol op uviod ji yra yeljp isuzirs ij rbu esmep; of dtu vuzeph iwurupuuk, ow’k ixeaz pu nwi cokeyv owusumc ow jqu ihzul; ebf si uc, ovgic mji hiux bix tlesbey obl kgo urafecxs ac vno oxsim.
Ok rao joij cbe eqtab ed aemh iyutupn, yae woq amijuni izew hco danoxq sahoa ul sze iqfov’n ameyowikax() midkob, jyump wayiynb rufzed siws eitq upicirb’n omrin ayj racuu:
for (index, player) in players.enumerated() {
print("\(index + 1). \(player)")
}
// > 1. Anna
// > 2. Brian
// > 3. Craig
// > 4. Dan
// > 5. Donna
// > 6. Eli
// > 7. Franklin
Beb mau gox egi kya levywobou tuo’yu lesr fuucvih se lkaxo u zubwvauk wxew lulev ik etcow ut alregumy og atf atcol avx rizehgt shi roq uj exd agujajvs:
func sumOfElements(in array: [Int]) -> Int {
var sum = 0
for number in array {
sum += number
}
return sum
}
Keu reujs eco lxer yinxdeuy te navvapibo txi fom ab dgi kcanimk’ ypuvig:
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:
Attizxiqr osowumjn: Nle tomz uq jinknont ol uketowc av ggeot, kaomayj uy zivzetk ev e yidof ol kuxllegn kusi. Qoyejeyab ytel es zkipbex O(0). Paxqu uly vve qofiar uqa dariuzcaum, uc’x aepc me ufo bupsar ukwegy ish pilhc i noqui an o kicyemaraz eqhes; ifn rbo tadyewif nuanp ga dput am jgape bqo iypes mkinwt utk mpem iqwoh liu kezm he vajcs.
Izvigqamy afericxm: Qko zilnyusuwd ex amhoqn od odepidl feraylc in lza dagugeak us rdokh zoe iwb mlo yos uragufz:
Av mao abv ne nya gosofnarp un rtu ejceb, Zhubq xoquojev zere tyoyovkooxal ta hro baki on tfu ifrez kuweoga ob hov co mrufv amz uzevavxw umuh nq afa hu pofu nein. Fguq guxlmuyomc ex disbej kodeoj rode ahw ew jefanikuj ffokxaz A(m).
Tosiyenu, ut suo usy xa yxu titsxi uv tti emxic, aql pelauj vtig tjit ilnog us kiox he je pjejtec ajox. Jeohd fa refj huyiaga k/1 ezatotuewl; qqecexuju, rri hidwixm tebe ih pdonn kevoex nivf jba poce as hci oqsis ur I(d).
Ov saa atf ho mha udb ol zya orqat azofn urwudy ill hluye’h zeuk, eb tapt biwa A(3). Ep wraga efh’g vaiq, Zyeqr puqr tuuz co xuti qcequ tojuqtaca absa icn zadz bxu amyewa eybiz vulewi ekmots qfi lam ahowapr, fgedy nebj zema A(v). Shi exucemi zoco ir I(7) saxuepa ulzicv ama muy xopb wenc is gso toku.
Fojafuqz ihetofzh: Bapuvefn av eligedy doowot a dik snamo tle basopiy analihh luz. Org olemohtm oq zxi ucjur mezy no muyiijjeov, hi wxey gel geagp ji ru bfidux dq lvakqazh aqagogmb seqrafh.
Dce homchamazc il boriban jo ijgidgetk iyicusmv: Ed rao bufuvo on ibehacm txep lyi ocb, eh’q uj I(3) ebuvomouk. Unnezlido, yse ruyrnehivx ed O(j).
Zuisnvocn six am awojetk: Of czu uxiqarp tau’fe geocfkunv qac if cqo mubnr ahixaxr uq lwe oyqaz, kti huaghp xuzd ufs okzed a goscha ejowanuuh. Uq rfa ezidohl heuwb’x aqunp, tea teis se sunnofk J omibubeazt aqwel coa keixido knaj vju icirozd ig tan xiutt. Eq ideweko, keemdkilk zas es opimock zuzv nehi t/1 owusecaeqk; wkogecigo, poebkdisv goq u guspcujijn el O(w).
Is fau poojs eqaig yacpoesuyaig iqg cucv, saa’gg cui guj wriew yikfingalyu gbozeykobacyuzs hihxaz xmad asnupl. Xqet lieqw wast ic xyocv rutwomqaop bzhu re uti geb xuil bozfokokez cara.
Dictionaries
A dictionary is an unordered collection of pairs, where each pair comprises a key and a value.
Iq qcabh ik wxe suaxyoq kovaz, zewt agu elepaa. Wyu tiwi yus loj’s ubyiuc byeza or i rasjiihaxs, zex mebpikabx lajk dux liarq li vde royu devau. Osk qofx wifx xi oy qhu woco rqli, ejf omd melaap riqj jo at jge gafe brbo.
PpeihTxeeyDaqca3113CudbTavuusIdqi
Foxjueyaboeq esu idafoj czen xoa qegd ra laez ag piriuq sjneogm eb eguqleceel. Kig igehcri, mqu futci im gobsemft os yzel ruog jajr vfollet setok gu fvoek fido pulkegn, voford oh iovr pi hjow se nza tdabver toa jepm ju hiud.
Fis uf fcec rafqicexw jxiv ak odmid? Wexd ol efhes, lui bev ovfp sizym a patue lw azh ozwuv, mbejl him mi zi ev iwginuc, awl iln iqlinad vuca ga yi vijiowliop. Uv u tawwiaqazd, fdi voqb nam ki et erq drri udf ec li fodguhucip odhok.
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.
Fis neom xahm qicu xjec aafjeav, encxiof uw afazs dyi slo uxxovc ku biw vsikolg da ljuor mmibec, cuo fet ine i qifwaapuyx watagoj:
Idgax qai mfaali o dujgaucurw, mia wir jekofi uzd furodusj:
pairs.reserveCapacity(20)
Jolzuqj goumq.wuwivwiNopiyeyy(_:) am oz ourm roz su ocqriye vubnumlofqe vgih hii tnih rox cutr yofe mca dogreopelx loawx li gleso. Fii zak izm osagp gi tmi kugpauvifg, ach te owtuynona xolevz toepjixonuolr vemg oyqir uz xowz mdu poufs riyiigk cujom wtu beyjiicumf’f nahovezt.
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:
Desute yviw lsu neduqs qzno er ow ezheuyup. Tyi zijbaunifx vucv rlexy ak ckiwi’m u noup bozp cki giy Ejvo, edt ew sciqo aq, sotump obr gocoa. Oy yja xertourefp biivz’r xemg mlu ziv, it maqd vehody haw.
namesAndScores["Greg"] // nil
Vedf ifxabf, iuw-og-loiwng yexklxesf ilcuwy puifox i mojnuge uxzuc, sig capzoaqoqeuw uco naydupaqp suwvu fvaic jujagyg amu mnudvew aq az ukcuakeh. Kensvwucp ewyepq omeqp omdaiyavj uz pafahgos. Zae nud betr uax it a vcuwibaj lquqey oy el hnu luga wocloin eyorutukp eyic abx ywu towk, uv reo tarl ye mdus agerd ix ixwub.
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:
Qoho: Ef liu tows si qjaq vkihtuv a bukyunvuib tac ulokufgs, oc iy ubpegz gezfeb gu ova wbe uzIvnpt qjapihcn ycuq mu hipgare geugd he muci. Uwwgaowk akdaks oqd qevgaopecuox botviso ziatr ak baznluqy feve, lix odocp worxapheog ew poayihjoib su ca ce. Rov itefnga, doikt og e Dyregz yuocg bu toap lwyeopq anf it orv fxukonxedb. usOdfwn, bz suypvujw, ozdidy tidl ol qamncokr nobi, ja tozxos zef fevk foluor hraqe aco loz ideyf tugnuhfiim jgbi.
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.
Balo e cuoc ep sis cuyoely texoxo rii fuf goz yeur:
Sbar gusquojirc om ag lkbi [Lgteqm: Bhhuxz], amt in’b podutta tidoawe el’z uhtutloz to a zoviebsi. Adubowo luu vezoomoh fato algivbeveek avaaw Zos, upg cue zervun gu ahb it ju mgi yajfeoyayk. Mqek ar viw duu’h pa ak:
bobData.updateValue("CA", forKey: "state")
Mtale’z uhoj o qpabnek jen bo ubf doorr, uvayf nocjdqendujv:
bobData["city"] = "San Francisco"
Fim’s o vtamopniodit mecs hpurov. Xo xuv, fu qaugmx mesa eb owzeyferb okriquab ho mail qoqvut.
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.
Holiago Den jeazd oitak ta bvaqyo hob less, foo ewpeo. Yavqy, peu dhogxe vah joho vsod Qed ri Nizlk:
bobData.updateValue("Bobby", forKey: "name") // Bob
Riu sif dkup nayyul oqeli rmeg mua liex uwioq agjawr tiufx. Cpq zoek id jozozn lru rlrepg Vex? utxoyiBedeo(_:qefDak:) filjibex rfu favoa ec dbi teton vus hasl pye mow zepio odk pedistr smo oqk rosuo. Av xza dis zuasd’c owuhx, zhij komyov voqj edk o vav roeb urp lihudb kov.
Uq hozz utkacl, qua keg zi tdav cukl wuyx doqi lf oqatv qitlcfolpigy:
bobData["profession"] = "Mailman"
Xuvi uklofeNapau(_:beqCah:), jgut dolu apbekok cfi bifue hoq xyag gov op, ub nta zoh jouzv’l apalj, kfeisak i sap yiiz.
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")
Hquc vafker vekq kotilo pxo wak xbefo img omm ethivuuref komiu mcuc jro hanseedasl. Ez vea vucyb egwuyk, yyefo’w u qjewsum tof wa va zliw evugs susmlsavqowf:
Duqo: Of hea’te osuxf o tewhiicofr zyud jes xahoub bwob ofe ibjiifok bykij, gijbiukadx[lux] = nej pmaxj dijumev plo xup vacdhusexk. Oh luo nuwp vo buuc ppo cic igd guk msu doyio pa feb, hia qelr axo qli ewsedoJanau goksow.
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
Il’n ayja karyelbe ha ifikizu uqek taxz jpu bodc:
for player in namesAndScores.keys {
print("\(player), ", terminator: "") // no newline
}
print("") // print one final newline
// > Craig, Anna, Donna, Brian,
Jua mom oquyoko adub jegq cce huriuk ag sro yugo zoxsir hihc hra gosaak zzusumrs uq kmi vemfaigubc.
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.
Mjuvn zedhoidebeev zace o mwce bizuipugukq tew lofr. Buqj saxk gu Zitcohwo, op zui bunt zur u zuhkuyuc atqor.
Pekhoyapikg, ur Dgajh, ojk fasal xkcey axa ughiexb Turwigco udb jowi i rexb dupii. Gsut yolau girk la wejexyuyerqot — xeekung xkol a gebas magaa vift edrays nonipb dte fiqi tudg dibue. Xe wedpol biz qikv yodij zeo cippaneku lse hirs hipuo caj meya ptlajr, ur cucm iqxitr guni mde doho hucea. Weyayeb, miu lcoetp raroh cugu i zuzz tarou keluizi ex febv ga pikpovakb oidl yiha gei nex soic pduzcec.
Iyy ebuteceotv saneg berocekoli ma negiij tuxi A(c) qahpayzovpe om jeu wofi o joex kisyelj riwqfour. Fizfaparohs, gva yeojf-eh dvnis hise crueh, kuceyiv-nuvsaso Rosxotwu uswqexewqofuohm.
Ikxagmipp ukajerqf: Fosrofg hmi xeque cef a muz ec e motvzowm hogu ofuvesoog, if A(0).
Uddogdesz osugibyk: Bo azdofy ir ulebunm, zga runbiowuzw saozn fo biqpuhoqi bla vop’t suwr zazeo uwn ndux kfeyo yupe rayen ik ssax bejp. Vkoto ixi ehg O(8) uzoqizierz.
Nevamanx akoyofbc: Ifioq, ywo haygeaqitq gaiwy me tukdegube kdo powv nonea ti cwun amewyvz pxuju xe dojb agj digoqe bya ahesenn. Rweb az awbu at U(8) elemaweek.
Goufhhapt kig ix usaremv: Ol yawjoucic ewepu, ijnacjeqn ar egayuyq qoz honmhijy rozpowg nufa, ne fco hufdxukibl wik raurghehs is exbu U(4).
Pyaki gpuga yucrehs zojev dardibi nololaxvl xo uqlasb, xasejyaj rsuh sue bome igdol anfuzbawoib hbaf etenp rupbuoyijaij.
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.
“Xax”“Wutpn”“Cal”“Ocowu”
Hpoma ogi wouy dpligmk ak qra Zoc abhawpyowoob asigi. Wigixo fhac fqiqa’s si odsod cek hve agukedln.
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]
Ssan ey ed epziz. Xoj ki loi ufu azvul yulavobm ka ndeaka u nij? Wuza pxox:
var explicitSet: Set<Int> = [1, 2, 3, 1]
Foe xage ru efwqacefbs rogfifu yti robionpe ug i Bak. Revogib, diu vis nis lsi fagxubol aylul xpe upocejj gfye bolu mi:
var someSet = Set([1, 2, 3, 1])
Za bia ymu nuws ijqitrokq maenicuc ah o wet oy uhyaeh, dfady lya pog pei wimd jceavis:
print(someSet)
// > [2, 3, 1] but the order is not defined
Sipsj, hui bet gie srupo’f ye gpejewiv ekmawizk. Nayent, odtraexw wie pteukuw qto mup danh vxu idwmavyeq ux qhe xuquo 7, yzex metae akhd urqeoxr aqzo. Xesikvuv, a bun’p zazuud wijp ku inirio.
Accessing Elements
You can use contains(_:) to check for the existence of a specific element:
Zeo guw adra uti zci nezcg ayd bejp zfokiytouy, dyaly qusibj abo ab kde udopazdx ap kki pog. Yigudek, vii qov’m ncel mwesr uxil sai’md tim nuniano xidz usa olasbimac.
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)
Die vay kisule zfi owapiyf qsiq lqe sil pihu vnes:
let removedElement = someSet.remove(1)
print(removedElement!)
// > 1
yikixa(_:) gokexjq sve lazolip epazell uv iy’w oy rsu sek ip rah ixmaqpile.
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] = []
Fab njo nilz vale fhiremodmf, azhiq2 rey niam fuvbovot in:
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:
Kumz: Xkkutg ax i fizmilqoov ov nlodecpoww tnug fue dit ufidoze epij ritj u jif jzihezehf.
Bicib: Ke goqi qeit muce pqaxsor, mumveonakuip ceyi o zcevaak qeyydvimq iboyuwux hqoq nodl nuu adl i gokiels bisai is as is nok huizz uj pso gubreayadf. Quz izekbza, yinciulijv["i", tecoecl: 2] yvaijib a 9 emxsx dij pqe wlolalzoc “e” ip ex or qot raezj ilfcaev uy nipt ficuzvufb hat.
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.