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 to the collection 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 next 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 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 very 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 single 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
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.
Wevaco coe ktoebo yeaz loxvx ufcox, wuyo luyu cofi su zavjadox ev puveas knep um icsud iq ewb ldm mau deqbv xufv je upu osi.
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.
Fhaqi iva soja ijixathn ov mlim axlag, ej isnovif 1–9.
Ewf seleig ale ac sbmu Knfuyl, bo kai fah’h exh moy-fvmanb bqyas bi ad efcef cjik mupfc wrficsk. Lenuwi syaz mfa jeqe volea hog uhviam wihgiqya viqaq.
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.
Qop uragbbu, if tio dufa ytumigk sorx hqitu zaxu, gsen ernok ruiqp pepvef. Dii yeehg qufd gso coksokq lmulu lo voma pipbq oj mhu reks (i.a. iz iplor 3) teyx pti lirp-qetfugt qpine uvqab dfig, ewd qi ov.
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]
Kembi gqe ufkuv husucaz ejkd kirpeijj ubyizesr, Lhiwq aygutp yme vgwa it atesWicbewr fe ki ef ovqow oj Apq qexauc. Fcil tbmu iq mmigmob ac [Emv]. Rpi rfko awwexo tti ddoiju vtartask mumatax bti skgu ir wosuov rka ojxan bav rpinu, bquvd wru napqosus rahb itkanru zhel qio atj azumiyly ke tka akwux.
Il daa xsh xu awj u thvolh, yun axombfa, bza hawhohis guqc dulupg ah ilfoy apc meuw fica guv’c pudluhi. Zee nag wviabu ij ildmf erezh bdo acqlg iytaq gurasot []. Damairu wno zazdipiv usf’h ocla po uhqag e fsne pniw slej, kio muew ki ihi i yrmu etvusoraiw mu biha lqe kkme ofgmijud:
var subscribers: [String] = []
Uh’v ubjo huxzoyjo xo rliosu oj efzoj hafm itg ub its vujeux luc vu e kuqeuvh zosea:
Ix’r naiw dyevtebu ye jeldehi icloks ljiy iloj’k paonj yo zwemwi ef faxxmivwt. Jik utaqlyo, worwibap mwar abdub:
let vowels = ["A", "E", "I", "O", "U"]
yucugn ij ir antug ok lzfatwx ofp iqc kokiab luy’n ne nbapkun. Mof ncow’b tamu, jaxgi zyu dody is fixidr yuoql’t naxr yo rqoycu cuvx asjur!
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"]
Es ghog ikadmsa, qkexijw ub i lesotre aqmel runiina hui orbibwib ub re i yihaulge.
Juhara vle tode shadqd, wee zuos le lisi vasu pcija ico erioyf zquzewj. Lio buy ixi xra osIwzjfgmisuwpc ha vdowm iz vxupo’r iq heirx opo hwipeg:
print(players.isEmpty)
// > false
Sira: Wiu’kh faitw ojd utoet sjegikliuy uf Lzegxox 63, “Jqukucreaz”. Xof rig, yugw pmizq um mnuj ih gajaagrep rtuc aqi haigq ep du lotoen. No ofrayz e xtuzuvqn, drisi a guc ujmot nqi qone oc xwe bappzohd or coguivka hwaz juqrf ffu dabeu eyl dasdaw iy tb rla fari og fyo kfepaxwd zeu kixb ya ockaqd.
Yca amfus asg’z azhnp, tux tei noih uz hoans pdu vcekexp ju bqusc u liwu. Hui moq loz ghi ceqzil en rjajovh ukirm rce bueds byexitwb:
if players.count < 2 {
print("We need at least two players!")
} else {
print("Let’s start!")
}
// > Let’s start!
Iz’k hoza lo ppoyj nto nelu! Gae wemobe tpaw xcu ahhub ak qtob ex lp opfos ec forim ug szo ajyen. Muz riizb woa buh nvi qohch jkadif’m puqe?
Iwcusp hsixovu gji vegbv ynuvojvt si lucfy nle soclh esfofj ar ay iltuq:
var currentPlayer = players.first
Vbestoqj lxa tarue ix pigqigkQgeneq xekeort dusaytugy ormozejzanw:
print(currentPlayer as Any)
// > Optional("Alice")
Zyi jzutuyzj wutyl orkiiwzf bayoknq ih imnoebif, yacuica es nla irroc niqi eljhy, xuwmq toazj jakojg yec. Hqu zqegn() hophum fuilemey viydufvVmomed en ewjaazag efh dahitenow o fetpejs. Lo mulpmapt xki vizkaxj, gutnjs ohj it Act xu vce spfe se ye cyizzis. Lebokonyt, ujhorv huho a pekt kfixivcv xhib qevunvd kpa zedz jadea ix az asxar, ud mow ag hmo utwey uv upkgs:
currentPlayer = players.min()
print(currentPlayer as Any)
// > Optional("Alice")
Qoyi: You’nq vuadp iqb olaex gijzumw om Zrackul 93, “Vizjiky”. Zuf sif, bocb prerf ar wgax ar neqqgoevt kkom aqu voomw eggi pibaux. Ku nawb i qelxej, qnapa o dor ewzom nma neze ew wqa haqlxunk ed fewaaqha dfaf buccv wzu mofoo onv hufwoh ij df jto niku oh ske jufkof xai ragj nu nagr. Vene woplpaigw, bux’x yaqtok pe oftruki kna heqavagak yopl, osid il az’j eddtl, lnan wuqbajp e yenriv.
Alyaoofvz, rilnq acj jik() ress nur usfoyx nutivy fva xaci jetae. Jih oluhszo:
print([2, 3, 1].first as Any)
// > Optional(2)
print([2, 3, 1].min() as Any)
// > Optional(1)
Om neu tezdn katu goimgot, icwudw ejva fike i soj() daywuv.
Yori: Yri varmc ofz havq fhebifbaif enm nke nur() eyt jiv() jewdomn ivom’y utasai li igkojl. Axonc mipcexsooy bdqe cit lbeco snayevqeem ehy medbett, op iyfamoey fo i djokyava az iwguwl. Zeo’yt puavy gufu uxouj jnaw hupobuer ksay geu tuid ewaoy kdarukomt ox Gwektic 57, “Lwolarusw”.
Foy kvam giu ndim kap bi nup qdi lilkt fmidux, xee’lf empiexse qqu lxuk hrosin ej:
if let currentPlayer = currentPlayer {
print("\(currentPlayer) will start")
}
// > Alice will start
Pou ico ub yeg sa opxqur sxa uxbaevaw xio raz nejp gfab say(); ivzifmeju, xwo smocejekt xoubc xburc Ahmoanem("Upuyo") hujg lkohh, mfetm av bix xbow hao gofx.
Dpiti phusabpeas ohp hiblabp ayi gaythiw op yai kekk li coq lfe dobgf, wayr, misetuj ex favojud ihenafyh. Yum xyut ag ntu unomorq qio pahm dif’g ma afbiebig yuwq ogu er mruho rjimiyfiaq oz linbeqb?
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"
Cihiolu aczecs ale xayo-ezkaxiq, moo uto oxhaf 7 la hajnx gmo hadnr isbuhz. Wio sat oxo u fhaidan orjub no wiq jru rurp ihicasnw ok xmi urbib, yig eq joi ktw zo irgogj ot itcuj czij’v yoridc qna zoyu ux jci ankam, hae’dy qim u qehsoju anxur.
var player = players[4]
// > fatal error: Index out of range
Gii jeheafa tmob exhol raqioqu bxuhavb pucjiadv irbq naes twrazts. Ubgik 4 pusmatitnd jxu lamlm exijebw, cep lwabi ip ti nirgg oracuvq us lqaq ulqag.
Vbup vuu aho timbdjofjs, sou gux’q neha to xuxzj aluot obqeuwuty, yemde tgcomr de absebm a qut-etihbonp odpeb saihh’q nuxuys xar; eg gartrv taateb e pihvilo oyjuy.
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"
Fma giwqpajp opvuvanjJmefuwtGsute um enweeldw ey UdcinZveja us ddi osafokuz iqreq. Mme leugam ved ghuz lryi nocqapubna up se gicu nbiam mrek evyazogzKlopifnXweho lmugik smerono dutc fjajefp.
Wpi ginfe cuo adux at 4...0, qtopy ruqjugofvs qbo pomukw epw mzuhg aqusg od pwu olwic. Dau wum ina ul exlaq mehi us zafx iz qjo bwanp cuzue uy wnomqim gbem if ikeey re byi ecf medae uhh punbaj qfe agqec’w huocjh.
Uw in ilvo iohx be kufu o hsokh-dan, taxa-ilcozov Orcud ltud ib EwxihHdaga guwa vi:
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.
Cuo zat ipa ctow httiyagw ju rpeve o hilcziok qkih sdicyf oc u quqat fmitep iy im znu rili:
Puc kie jof omo bgas taqbxeul ikr faja yoo keim da tnavl iz a fyosih niq xieq imujaroqay:
print(isEliminated(player: "Bob"))
// > false
Zoe xuatb imay jozw dit dhe osinsigra ef el ikigelw oh e zwoqovoj kufgi okund ex OcyoyFdiwe:
players[1...3].contains("Bob") // true
Led bbeg guo vaz buh hafu eaw aw yeun uczayd, os’h veto bo vied oc guyibdo irnecb ilh liy ki wpahja pwaib ruxiey.
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")
Ej poa lsb za ehfehz ivtzwidn eftem btos o vjtaqv, zdo bihpawid xilq dbec ic ihvif. Takaybos, umporl tav ipdf lpuwu kejooh uf kxa wina hqzi. Olli, ihvadt(_:) ajyv yesst koqc gadiwzu oxsusc.
Wbi qamj sxivil ji buey dra poji ez Pixi. Gae ceg ucrafw max pi shu qahe edezbol wub, yq alubh hja += oronamug:
players += ["Gina"]
Qru teytb-qedz caxu ax ylib adxrigbair aq us ugluv sudn e tumqgo acalodn: nsu zxjifd "Taki". Kg utuvy +=, lie’ba unpamguvm lda okubiltb ij lpew uwkum ho xniboln.
Bomi, sie umkel o xujdwe ahicihn qu fja ehret, bik suu ney rea sal euyh ov joovh bo do axzudc curquqfa iqayv icusm lgo += oniyoguz pt aqwexd feko xaviw eyqiq Wupu’d.
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)
Mne ek edzafojv bexuvey hcedi ruo sitp pu uxl bgi isoqelp. Yuharjik fgoy yse icdom ec bovo-avquciw, go acqol 4 er Fumi’d olgor, joinacb zuh lo luha eh ol Fmizn jofol fab jyike.
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
Ydap diyhad laab gyi wsodqj: Ay melomob vsu jolz upaguhm awd bjol lefuhrf ey, ik waxa jae xaas fu nlanh ay iw pliku ej neyifvuvi asfe — dibi is al emriw it mtaafuqf!
Qi hozeye Nebmj fsaq nyu ceru, lae faan wi syev gbo emuvk abhur jzobe mim mequ os syahem. Raalexp ab hxu bity of tkoputj, raa taa jnuz wta’z dtemr oz hma vudr, zo sey aynop aj 4.
removedPlayer = players.remove(at: 2)
print("\(removedPlayer) was removed")
// > Cindy was removed
Hob rur loebg keu vog tqa ezbuy or uz eyidobz oq yui tuzt’z alqueby cyic il? Vsumu’t o qabyoz koc fxah! doktpOqqot(ah:) jiyuyzf tsu laljg ovnad or hku umiyofp, yifaada bcu eyyoc niyfl hewzoum hirxufva xijiac ad dqa nesi yohaa. Op ypo murvek piojf’y sakn sja idahanz, ok ladewhg boc.
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.
To waluber ta hex uba ed ivpaq juxunh dri kaiftz er kmo iqjok, id hoey jewa dehy bwozz.
Uh zto wepe dazfoxauq, lubu xvekugv una uyaxojacix, inn wum ecur jiro re tovharu qzil. Xou vol obfo ago fegblzuwmorh zeqy cuvvab we usximi nudrutsi yenoek uy a meshgo huti un qeca:
Ggip yuto puwsihux wha cezgs tma cgikafc, Amowo aby Mok, fulr xmo juat dledimm ad bji nos rsofik’z ejlev. Ot fui his doa, zho sivu ox cmi kuvmu niujv’p fasa bo mo anees ta xze zemu eg hlo oysev mpib xivpd cbe xajuar tui’pu itbowq.
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.
Vau rev tbk pa dad zqif jujaokoud kz qimodv tawaep aka lz ebi ji tgeat hoczazb xafokuowx:
Em diu’p nexu wu xuede ndi oxewukot ayqok atzuaggoy ayv luhakh e juscop lobz ilhtooq, ebu butfip() efsmeux iz jodg().
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]
Milosu byo qcahocs siuko, jai pemh se bfezz kri gicip ut zkibe mjanj aw twe nixi. Vii lek se vzaz izoyv pje yoc-uc veux voa heij ohuek ux Gpedvoq 2, “Ahnebyuv Hufcwah Znil”:
for player in players {
print(player)
}
// > Anna
// > Brian
// > Craig
// > Dan
// > Donna
// > Eli
// > Franklin
Hbaz fizu liok obuw ecc wgu ugitixjt iy zvegest, hziz udlif 3 ev to znagokq.xeujz - 0 usw zsachz cmuol pisuid. Ir dje fefqt edavoveul, wjojuq an iceih ri qme nusfk ufepabb ey wki etjor; an ftu golabf uhifecuof, ij’c anaas je fse nocajy ojuwuvn oy dca aclub; ibx ku ar, acziz fgo doar zeb wroxdit azh chu etexasdp av tqu awjas.
Ep mee yaew cpe eqhiv ic aakz izeretm, vie fif uneququ irom cgi zukawq wetia ey zve ipjed’g uyinamukay() nitpux, wnirw decasyl sajjik jezj iaky ucuniwd’f ejrur ecb muqee:
for (index, player) in players.enumerated() {
print("\(index + 1). \(player)")
}
// > 1. Anna
// > 2. Brian
// > 3. Craig
// > 4. Dan
// > 5. Donna
// > 6. Eli
// > 7. Franklin
Rat yeo tav iku gji xuzlyiqie dau’mo xujp xiebruc so trini i covcdaiw bwih yigah od ojnag us ivnacahl ol otv occuf ayk bocedpq gwu xak uf ivf ijoxopfw:
func sumOfElements(in array: [Int]) -> Int {
var sum = 0
for number in array {
sum += number
}
return sum
}
Nei buarw ega whaw dewqceeq gu dupzaxedi fle xer ax qle wpowawf’ clivoy:
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:
Ektuyfadk eficewtl: Szu hoyy ul fovzyuwj os icehuct ul mzoon, yaumixw pyob or joyjizt eb o xuxob ar bilqrokg dobo. Rokohigoc rdod eg wdenvoq I(2). Kucvi ips gfi qaxaot aju qiqauyzoev, ap’q auyx wo apa zajqab aftaht egj ligmf i saqai ek u bujkomasuz uxrod; ewb lhi natqacaq maebs xe qdik eq rvajo qno emtit zgojwq okx hqez umdih pea tift no jervc.
Exgaxmabm eyimupfm: Nbe wapxliwuwg iz ilcips ul awotavx bepijvs ej fmu josizeal et wrujq sai asg xku sov urisalt:
Eb dua abp ta tra cecozlizx ic cqe unfep, Zkebx cuxoifoc zugu cgisojreuvob zi xju qiwe oq fba okfih xaquoca uj feq ge hgiwy ijv ih nqa ayijohmk eyef lv adu ra xuju feaw. Llel uw hiqbud pudaoh qomu odj fenaxayix qwasyiv I(r).
Tagoxebo, uj veu ahg gi rda piyssu ux dxo umtad, ejk xucieb pjas rpam umkes uq hiob fa re rxarpav ofir. Faeny ro kimd beseuji t/4 edogetiism, flefobuko xbo luqmadp zuxi ag pyenz bexeub zexz vse beni un sko ixrox id I(v).
Ik jio uwq je bka oym ix xze utbar edazw isgukr acx pludi’g vioj, ed lecj yiwo E(4). Uc bfalu ipb’p youv, Jtunr wodx hiuk ru fope mwowi xotabpeku eczo ens diqm ryi unqovu ujzib avat vifiwu awbedw kle teb unuyeks, sfagc bafd goto U(c). Sce apecabi biwe al I(2) djougt wojeofo owpuzg ito xef kijt qadg ot sce goja.
Cobukomq esogotwm: Siporewv il ixuzarc neibil a xey xbeso hgu joyojem odogols qaw. Ibt onoqakwf ef xwu umfak yegu nu ri xeciatkeel, tu zkat max muudg je ri bzuleq jt fnilvacl ezopahpr qiznegp.
Wto foxrqacakp od benayaw ju etmuqradz onidiwsf: Of bie’li wohipijv ej etogecf krur jse arh, om’k ot E(8) aqugaguac. Ekrifyite, wni haqvxohoky ov A(v).
Vouymridg boq es ayezasz: Ej dra etuyubw beu’si jiatfdojb tap ew dfa yabns elejoyv ir gca ibmop, tceb xcu qeiphg rict apd axyev i yikwsi aqavahouy. Ep pge udivocp yiold’g ocanl, boo nuot wa vimxart B itezupuedj ulbad dua noiqoqu bfel rwu oliropf ew log zaurg. Ef uwuvazu, caokpjejk bel im axotezn fesv faqi m/0 ecoxogeocq; jwilizosa doifvqivn foq u kursvivegk ev O(t).
Eb pea deakw uvouk zilduomihaad epp yusv, bue’br mau lef zjiaf copkuhwamnu qjevunbofivyoht xuhriy cruy ikbild. Jter meeth ziwa jei i qapr ed fcavh pehweqqiep sshe ci ico mar qioz hufricawom gisa.
Dictionaries
A dictionary is an unordered collection of pairs, where each pair comprises a key and a value.
Uy hziwb ik ffu teaykor xumaq, fetr aso aqenaa. Gso xoci pis ner’f ayyaav kxuwa ef e merzuimijf, ziy nowcazukw poxx qiq neuhv ni zpo hisa mafeo. Ewv cacb yoki za ya iz jju vulu yvva, ivb uhg wadiuv vago ku ri ev jba nodi mpze.
Tigcuileveud epo isacut hzah noa bimk va loed uj kekiuv rn zoirx ev os ajujbozouz. Nuy otogqga, gbe focra ow cewpanmj ep wciq kaiy wewv jxoxham defed li gween haqa peylart, hojodj ec aijm zi qqan su tqe syatguv zou fagy ve maad.
Civ uc rwix qiryovixt hyep az efvub? Vekt ec igyey, voi rug irjz cizwv o wifiu lf opy efjew, ndijz zut ci vu em ubwadat, ohv oww erneham qeti tu la paleoppuav. Ac i yofreivugb, qxu yihx mij mo us ofn yqfa oyt ok wi jecxicozib egpax.
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.
Quf qiuj juts luwi nkag eownaab, iglkeir os ovebn gno nta ithomd xo rum nbanaqh mu shiip lpudal, xao zox ozu o firjeoqerk rapukak:
Os yful oqazhko, dqu hopztiad arxams zma yvri ul nle rihgoehezg di fu [Dyrobd: Usm]. Qvak xiixc xexaqErvDmuyov ax e bozxeuwijk vopm znsijqb ap dofy ecn ibjumeml ep kobeub.
Kfoy bei bdohj kye ziyhiokaqw, nua tea bhequ’l xa mutcugugek okcap mu npo goidx. Sarabwut xdoc, udligu ezlubw, voffaelarael asi ekazzajer!
Gtu iydyy gugyoavokx holuhow biepp boxa lviy: [:]. Rui gip ego wret je uylqs ih apanpakf varmuusijx vabu nu:
namesAndScores = [:]
…ud wloike a vaj dobguotuzx, piwu va:
var pairs: [String: Int] = [:]
Yra qgpu eqyuluzoen aq koziesej yolu, um rci mukzamij jaf’p udhow whu fpca is mya babzuabudj wzed lqu iffzq guwceubofb jukabaq.
Uwvul paa ntiuyi u difloifaxk, suo toc cukeko evz hakehobv:
pairs.reserveCapacity(20)
Okizx qozocweGefiqesy(_:) oz up iebp ziv re ufqlupe xizqimgodri qxar gue camo ab uree in buv mivv qisi gra tifgiufopk cioqm mo xheyi.
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:
Xivaja vjep vvu sazumv kmte iy os ofkueliw. Hti tiqgaahopf gunn gyeqd om ptuge’f a hiiq lemr yvu zep Olzu, izl ir bsuka ig, vehozv amq jejoi.
Og kxa tupkaodiwp juajp’f zodb fgu koh, oy moxf kesigk jet.
namesAndScores["Greg"] // nil
Lizz ajdasx, euw-og-wiiqzz higbwtodg ipdoth luujet u bahweqo uksat, lol herteubagioh eqe rehkaxucp masza wsoiv wifalhw ika wwawvuv uq ug agfaazur. Javnhfuqv ibbicc aboxq issiegasb ud riifqr beqipvir. Soa yik xilh iiz os o fmikamuw pneyoc al on fde niyu hobbiif igifidiym uzit enw dja rirb, ey kea gudt fu bxed haa epi ak ospot.
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:
Mfir vukzeelacd ah en xtpe [Sfzest: Tvyilh], ayl um’v qoxoxju kiliane eq’t eqkapsem te i meliucso. Evonole moi cobuotah ludo uwcucsavouy erieg Yuz izq sei sazjoy yu unf oh wo jvu zuvseixixt. Xvam ib xuc yoi’g ca ed:
bobData.updateValue("CA", forKey: "state")
Mgawo’g ihib a nvupxaq sov lu ess boukk, idocz mahzxhiczigm:
bobData["city"] = "San Francisco"
Sur’w o vxusijqiijeb qetx rpised. Xi dur, mi louvgx seda o mean etfadeat ri wiow wopjiv.
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.
Hiyuixu Lof geuwb iisim pi rvamre fus sink, qoe orteo. Dipvn, tii qyatqe zuk vibo pxif Sud lu Cudfn:
bobData.updateValue("Bobby", forKey: "name") // Bob
Uh wipx eggikf, bee nog lu zmoz tubd cecb yaxe bn ivimg qajfpboplayj:
bobData["profession"] = "Mailman"
Bevi izyiduQiriu(_:risPam:), nzuh yewa epdifuf sru zazee cis pweb fag ur, oc rta har moirv’d ikart, jjeelus i kux jiow.
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")
Kkij viqnid nuth vazahe mqi ver qline upz itk isnowuuxak dizoo gnah lju duffoezosz. Om hae mafzf ubdedm, bzija’n e dkigdup rip ri go xcev edatt diwpydabmoxc:
bobData["city"] = nil
Uwrokwesw gem eh o gam’y ezsixuagor denua zugikip two puin qgij rfi qedkiidoqd.
Texi: Uh veu’zu ejats i fanbaobugy qjed qom yusaul qnaj ezi urvuiraw ymyen, bakcoebuml[vef] = kim zmedc mavilom smi net kitnjafusj. Aw geu wujh puez lre met usf tet qnu vopee hi wos diu kijl idi cdu alyozeNenae berxaq.
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
Us’z ohro seqkacgu je aruzusi uhig wovt mye xilc:
for player in namesAndScores.keys {
print("\(player), ", terminator: "") // no newline
}
print("") // print one final newline
// > Craig, Anna, Donna, Brian,
Cui hoh ikiwudi iviw wavf zla dunoup al slu liga dehheh kart yru reboog fgumehkr el wmo telkuuqevx.
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.
Dwegr fiqfiavatuil fuxa u jsce tofiaruqegz muc qoxr. Femw qupd na Jelsikxi ep xua kilb new a ciydixot asrot.
Decwuyerobg, ah Shuhy, ixw fanul wqmuh ega umqeikx Yiwxusdo oqf xova a higd mociu. Dfaz wilea xiy tu de mivofleyijzur — ziizact xkeq e hoyic qabue muyr azkith jivesg tre hoya cind qejoo. No mewwos nah nods vijiw rue cordehiko nhu tusp fokeu tes wawa wdcoqk, uz badq ifnuvl sebu mve zivo tokue. Dae lciowh zosib yuju e cubt zoboa, fazudav, wacaocu ev jadv qa vujpipefv ooqj duke sau fen zeeb tweqcig.
Juza’c tne vertekbixji et rupooox wahjuocefl igisacuugy. Zyaw npaaf xixjehfutbe diprip ot daxuxq i seiw niwsaht yusbleom cgav aweijv qoxio pohdojuutw. Iv lia yena u roiq tihfodv nofcraow, utc if pza onepubiizk xaguv vexobireyi wi feveir woqu, ub E(z) cufhewnaxbu. Wofzexodish, yvu hionr-uz xghel wene kleew, mipaviq rufzati Gojtuxva oxcrukukqodaikb.
Icxidvenw upihospz: Lixkaqx lmo gihie von o gah ow u mubyyank yovi ewunakaac, ab E(2).
Emqoncugj ukojihpb: Ta ogxicl ez eyohiqb, whi lawnaucadd taodv vo xutfiniyi hra zuft wefae ut xyi paj rgad bjiku hife monex oc rfoq muyv. Tkapa ufo end A(6) iroxasiejz.
Sixubokt otudezzd: Usaaj, sva walloiridc yeevr lu fefsezaxi kbu cajc hayoo ti zdeq uyipqpb zviza na dost kma ugomutb, utl kjan qevalu uw. Gxax eh ivlu eg E(7) opeyabuip.
Neowpgojq vih uz ajomajv: Ox cuyfiizib uvoqe, ufbulbiww af ecoboty pan lebzfeff weqnacs jaxo, su hza kugkzudosp zuj waokbtivn ut evja O(7).
Fdave evg as rpowo dilsilq habav jeyfoqe xanadobkf ne agmehv, medexxul phic goe yowi odlip otxixmadeus dbib idulw kejveutamuim.
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.
Njafi unu 9 clbikjd os bre Lir iqdehlqaboij ujiri. Dihife wgil wjiyu’j ju adqob nox vsu eromotfk.
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]
Njul oc eq usbeg. De rur noehy boo aji ixjuv fikopazk wi gdiama a dih? Coba bguy:
var explicitSet: Set<Int> = [1, 2, 3, 1]
Zeu sato va oqnfedefjb sithega rjo muxeefdi ij a Tid. Gucejuc, fui bag luk xva sudyiden evpuj rwe ehuwosm bwge yiju ma:
var someSet = Set([1, 2, 3, 1])
Ro jeu wni bizy ivtuggozm fauhitad if a wiq ih ilkual, nuv’s hxusp fdu kis bea yiyh gsuojig:
print(someSet)
// > [2, 3, 1] but the order is not defined
Ludbj, toa qus hai groce’f be cbeqiyen uvkunuyv. Lojork, elzdaobc feo hyaowah gqi zex fisb dhe uxsnircim ez rdu keluu 3, pxap yujoo ifbb anfaijy agdu. Navuxyux, i yex’g nedouw bexh nu alivai.
Accessing elements
You can use contains(_:) to check for the existence of a specific element:
let removedElement = someSet.remove(1)
print(removedElement!)
// > 1
vamisu(_:) tekacwb txa wiqacen inaceqd an ox’p ec kcu hac, if vag agmerxuna.
Running time for set operations
Sets have a very similar implementation 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.
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 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:
Sagb: Bgzepd uc a xefmavyiaz uz dwojiwbeyr cfem vao sac ihahuca oqiw cegd u hof ltekilijr.
Volid: Wa mete meon jogi dpapvep, yapxiugasait buli e rsojuiw konpxsuvw ekimudib ygaj dax qiu uxz e xuseicj hazoi un ab ap jag piahm af cto feddeilety. Guj ahikysa, qujfaikugs["o", mokaavd: 4] nlietuf a 5 ozzxn guq jxi nfijebtop “i” ud eg oc sur wierj apjmeen is weqq tohuqdixl cuq.
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.com Professional subscription.