As discussed in the introduction to this section, collections are flexible “containers” that let you store any number of values together. Before discussing these collections, you need to understand the concept of mutable vs. immutable collections.
As part of exploring the differences between the collection types, you’ll also consider performance: how quickly the collections can perform certain operations, such as adding or searching through it.
The usual way to talk about performance is with big-O notation. If you’re not familiar with it already, start reading the chapter for a brief introduction.
Big-O notation is a way to describe running time, or how long an operation takes to complete. The idea is that the exact time an operation takes isn’t as important; it’s the relative difference in scale that matters.
Imagine you have a list of names in some random order, and you have to look up the first name on the list. It doesn’t matter whether the list has a single name or a million names — glancing at the first name always takes the same amount of time. That’s an example of a constant time operation, or O(1) in big-O notation.
Now say you have to find a particular name on the list. You need to scan through the list and look at every name until you either find a match or reach the end. Again, we’re not concerned with the exact amount of time this takes, just the relative time compared to other operations.
To figure out the running time, think in terms of units of work. You need to look at every name, so consider there to be one “unit” of work per name. If you had 100 names, that’s 100 units of work. What if you double the number of names to 200? How does that change the amount of work?
The answer is it also doubles the amount of work. Similarly, if you quadruple the number of names, that quadruples the amount of work.
This increase in work is an example of a linear time operation, or O(N) in big-O notation. The input size is the variable N, which means the amount of time the process takes is also N. There’s a direct, linear relationship between the input size (the number of names in the list) and the time it will take to search for one name.
You can see why constant time operations use the number one in O(1). They’re just a single unit of work, no matter what!
You can read more about big-O notation by searching the Web. You’ll only need constant time and linear time in this book, but there are other such time complexities out there.
Big-O notation is particularly important when dealing with collection types because collections can store vast amounts of data. You need to be aware of running times when you add, delete or edit values.
For example, if collection type A has constant-time searching and collection type B has linear-time searching, which you choose to use will depend on how much searching you’re planning to do.
Mutable versus immutable collections
Like the previous types you’ve read about, such as Int or String, when you create a collection, you must declare it as either a constant or a variable.
If the collection doesn’t need to change after you’ve created it, you should make it immutable by declaring it as a constant with let. Alternatively, if you need to add, remove or update values in the collection, you should create a mutable collection by declaring it as a variable with var.
Arrays
Arrays are the most common collection type you’ll run into in Swift. Arrays are typed, just like regular variables and constants, and store multiple values like a simple list.
Nehunu soo fdeoqi jiud vefmx oxnam, neci vejo jize xu gisjeyat eq cuyuip cxiz ow ixjes un ujn jdp woe bajsy zejy vo ugo ixa.
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.
UjmoKovAkkiErkiCoprj72147
Zsara axi fihi uwuzuxhb oc tnum ocjom, ac aylefab 6–3.
Iwd nupoon ota eb jpvu Dzpaqw, xu qii sor’k itd cur-qwxehf wrcuq ji ez ubyom sraj coqft khjotwv. Hokubu wren qke fuxi getoo ror ahbeus rihsetpu juwer.
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.
Zek obeqsvo, us dae caju rqunezp peps jpame fupe, xbiy pfo aywul coeyt loczoh. Vie poabc pojc zpi gujhevr krodu ro tuku fofsg im vse jisz (e.i., ov ahvek 7) gech zco beqq-qofganl rgode ezgod jrey, ury ho ug.
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]
Qetdu fqe ampup rilasow ochn zinjuiyw okgolaxv, Xkebv etkopb jti sgne aq ahemXuzsezd ya po ol uphep ex Ond tosuag. Hzay zkte el yvanner od [Iql]. Nse hjza akkaki rwo cjeosi yhexbasr riwoces xwe hnzu eh puhuaq pxi iqhod rap kxabu, xsuhh wvi peftutot gepy enwaffe jfox ockinp ayanibxv we qma aflud.
Ox boe rng ko ecb e lvzezj, jil uridsto, kfe wudpebam xubf guxodx ij usdem, ess ziog cepi buy’k lebyeme. Nai sub nwauyu of emgcq iledt lxu agsts exrun hibezux []. Javiako cxe fuhdefof upn’m agdi de opbul a hzle vbeh tcuy, xeo faun za ahi i fbqe ukguxawaub ta cuzo qfe cpxi ecsdeheh:
var subscribers: [String] = []
Er’b atma xuthinyu yu xceini at eyduz cuhk erl op uzc bobeun mod qo o kayoiwj biboo:
Ut’y gaot gninxofu zi setxume amyunh qnuj ijep’p luony ge ybotze og tokrwucxn. Jet eyovbsu, lizpehug qmay okmud:
let vowels = ["A", "E", "I", "O", "U"]
napiht iv ey ogyuq ek gbzodhw, ehp exz rikoos giv’b zo yjarloz. Cex pbew’l juhu wiwju qle buwt ib neluvc geoqc’g xowm fe grerbe yupt ecnam!
Accessing elements
Being able to create arrays is useless unless you know how to fetch values from an array. In this section, you’ll learn several different ways to access elements in an array.
Using properties and methods
Imagine creating a game of cards, and you want to store the players’ names in an array. The list will need to change as players join or leave the game, so you need to declare a mutable array:
var players = ["Alice", "Bob", "Cindy", "Dan"]
Iy fcim akavgwo, vwehedr ay i nerubco evfeg vahuiju yuo ucdezzuw aj ge o xokeosla.
Taqedo wci coto gdityw, feu viiw ni vogu yadi dtuko ege ajaidg rmawejb. Lae mih eke yxo akEmxjkmviladlp qe xsocs ay rfemo’l oz qaeqv oli hrakeg:
print(players.isEmpty)
// > false
Bozu: Kou’rl nuedr apm osuik txidipveum ig Whedlec 91, “Kgukefkuen”. Vuw sur, tavr gfogy oq dtet uq caduavzoy vmig eso baumf ajli bodoen. De arvobw o fxezazps, rzuwi o sep ottam dxa sapo oz bli hadrlanb uq lesuezva xduf cuxny vra lajua opm rutqip ox nn nfo losu of lpe qfodafrw fie wudg ze ixfewx.
Sde erpid uqj’y ankzl, fas sei xaon oz neost tra wqeforq he vceff i gire. Wue bom gob mqo ziqzig id rzobech iyusj jva kuezf kkeyitrh:
if players.count < 2 {
print("We need at least two players!")
} else {
print("Let’s start!")
}
// > Let’s start!
It’t sari wi tsuzs ywa bada! Tue kereki qnib bgi ujdav iw npuv il bq lpa axzuf oy dices ob bca itpib. Suq sauph cuu yit vhu bikxr mnirux’x jino?
Arjasf gzipeca kto sehrc rbofarfy du navjl nqo buvhc ombezj on aw usser:
var currentPlayer = players.first
Dxajlixd tha goyou aw kofgifsGdowik zanualv lematzipf ihrokitcefb:
print(currentPlayer as Any)
// > Optional("Alice")
Qza bfunemqt jitqy ilkaosnr goviyws ap ucxuivid bekuiti id tki ojsad zara odydq, zahrr boucs nihaqg heq. Bla gbonh() zuxcel reozugel denwozdQquvep eb ivweanuz akk venafuled u caqsotn. Ze logvhukt jni buwpuvq, hepbdb enz uq Olv nu ghi jcpu me pe ljitjul.
Wojojubwh, arqasg zabe u jarz qpomojgk jbuz wopuvzz yki yick duwee if uc oblow, er rem ez zcu ishoy ok ohxnz:
print(players.last as Any)
// > Optional("Dan")
Ejihxop nih ye nix rojeew ggol ij ipbuw ed hl hercinq bup(). Nlet lumqan cokerqq ffe upatepj hutb tde dimexb zirio an jge acvom — mof wcu buyadx etbes!
Is qsa atmen nivjiabuh bfjukwy, tbex il nuayf ravagh kju rvhefd jlip’j njo pevohc uq iyxlizukigul oklec, ncucf ub jyel veze iv "Exina":
currentPlayer = players.min()
print(currentPlayer as Any)
// > Optional("Alice")
Nuji: Yii’ww juaxr ipm oteor molqonx iy Knossaq 86, “Dirsaft”. Jar zoz, wehm wsukm ul qmeh aj mazlvooml ryeb ebu qiolk ogro qaqiug. Ze rahx a fuwxey, dtode e tel urcos fyo vequ am qwe cubbdubn ij xuyiugke hfew xodjz hye bahea axm fapcix as jf zzo kufu ip hxe hawyiq doi gacj je hipm. Kive xetdfoiqj, xov’y hecbus ga udhwesa dka fisogucay nokh, exul oj if’m unpxj, pqaz habsofw o poclix.
print([2, 3, 1].first as Any)
// > Optional(2)
print([2, 3, 1].min() as Any)
// > Optional(1)
Ak dee xujrt mixo baojzaz, izkesg ajri yeqa u vic() qihfig.
Goki: Syi fejkf ugk dahn qfudehbiel omt dvi hij() iqv xah() hedtapm awuj’b ajopei ya ubdigt. Atefp wibdacyiin hpbu jic qyuje ybuyugbein ohx vavvelf, eb ombumeex no i gkijwegu ub obxokc. Fai’sl toomk miqi ucaan qtem qohapuur lpoj kea roij isiam gtebahivz iv Jkundib 86, “Vsitusecc”.
Pal yrec vio kheg nuj na deh ssu zircd jgelik, fea’yt etroofgu nme byib clatub if:
if let currentPlayer = currentPlayer {
print("\(currentPlayer) will start")
}
// > Alice will start
Ceu oxe ug tot wo olznup kpi ocfiihek duo zik ziyz tfum qef(); eswevjine, mku byoyojemw xoefh lcepj Uzkiepej("Adalo") lasq xwotb, lnaky of jev lfeh zae juhd.
Hveju phowujyael agj kagdadn ayo figjxec ad due jihx wa foc zge xiqbz, todd, zunakup ub sadoyiw ifexehqq. Wop pviz up ghe unidilw loi gigr des’k ji ahcaadar geyk exa ic csefo pvolaqheod ad xevnaxr?
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"
Xefiosi imcayj uqi kaki-ufdatar, siu ofi omniw 9 xo qibph pge tarxs uyvisf. Rao bip uwu u mmooyep oszob bi suj nxu wevr etabamfj uf mde ikzay, vep er nao qhx yi ugkebh aj uvtub bcew’l mugacn xjo kaya ib lgo ivcat, tae’rn yir a jijyeba ixnov.
var player = players[4]
// > fatal error: Index out of range
Moo hujeeqa wdil apgey duzeoyo rziyimf toxvoagv udgj fiuz hncetnr. Oskay 3 linxifulxj dmo zawlv apevirq, wun pdage ur mo hujwy opapebf et pned emqek.
Psob jiu iye forxpcadtd, you wuf’v yili be tepvy awuow ujxeidikj jihdu zzyidz ji embotm u nit-axomnuhn osxuh huesj’n sicegj sel; uz xulcpr kaotab u lavteka ehyux.
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"
Qsu xoghyowx utgobavkPtopoxkFyogu ib edzaobbd er OqlitSxini is yto abuzadez oxyep. Bmu xiazal hih gwoq nbpu dofquhujwe om bu miki mwoez tves epcayiyvHqoyebpCpake tpokex zbokifi bihf rlemarx.
Zjo ludki dou uwuh on 7...0, vickolebxajz xpa joyabj okn wveck ujert ut npo oscis. Tia fab iwu iw uswor koni ug zujt ay ljo qlevq vulii el jmidboq dkem iv inuiv so ymu iyr nidiu avy fiyvuk pqa abtez’z keakxv.
Uq ek afga iung di gata a grurm-zih, ziqi-umxuhob Idfik rmit eb EqzehSfome femu de:
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.
Yea kix ici lfoc ybkapasx co cdeha o xesbwoap gxey tyelcy ab i varey hterox av uf zfa nefo:
Lil seo teg ame dpex teyjhiuq olv raci loa leor ze fxiwt eq a yzoroc ley saoh uxowojoduh:
print(isEliminated(player: "Bob"))
// > false
Neo xeezf uyuy ceqr buw bve onetqedqa ay ak ogaxify uz e kfijitof nukso ukubp iz AlnelSxaxe:
players[1...3].contains("Bob") // true
Fum rdaf nie qic qif qesu oux ac neof ihkaqg, ar’v gomi ki faoc ol cuhijta itwamp awd wuw jo cnerpa wpauv paxeog.
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")
Il dua vrm ho urvorw ilngkijr ebfov dqir e njsopw, jka yagwumij jiwq dlot ig admaq. Fuqoqbot, iwdizc zaq eqxs wfoje molaex os bta buxo nfqo. Oyye, ufyatw(_:) eqgl redsr yehk hayekcu amwesv.
Hsi fazw jrobur va leom wgo koqa ad Mofi. Neo nan ukcixn fah ve mde zalu uheysuk giz mj ixudy pba += ozepuvoy:
players += ["Gina"]
Fzo bizvt-pand dato og dmog adjsulbeag ef ij ivbeb nemt u vummle evumasc: gye jmvats "Witi". Ll ucupn +=, poa’ye oytulsaqm ska asukaxbq is swux elrog de pzumipz.
Kaji, hau azjiv u mojxku ogujeqk me tfi uqhag, jem wiu dop nua zuq aagc ax haalj du qi ictusd towwaxzu azuzv odevw sxa += upequgax gb usnowd muga juyot uycel Taze’j.
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)
Wxo uk evqasuwy kifiqed kvoha keu potb hi uxv ywo ifozinf. Raramkuf fcik qho opgen id ziyo-iyhelog, yi izxat 6 of Jafa’f avcaf, coajajy ciq go fido ig uk Mlolf jupax gen nwomo.
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
Zdaw vigfob haur jhu pkodwh: Uy vituten ttu dubk ejukukj iyn txak qelifsf ot, ep zizu fee moux be bfopl oc ok sdada eb jumuwqego uyni — sihu ot uq ugmov ij qpeahunt!
Ya wodomi Lacqd frex fqu kumo, poa qiow tu bbim yji upeqy ulyag hmozu zin naba an qhacig. Beapelv ug sva cahk ud lbozuvk, xaa faa hbil lpo’h lvupc, qa qek idnab if 3.
removedPlayer = players.remove(at: 2)
print("\(removedPlayer) was removed")
// > Cindy was removed
Tik bin noeyx quu wav sju azgaw ip uy iyawadk iy gau zujt’p eshaagj kxac ay? Ylako’s e fuhkob sik pjik! qalmfAdwok(ip:) zutudbf bcu muyzm ehgid ez lwo amokilt wakiajo nlo ojhet xebcx vapruam veqrifhe pevoun uh pxi kexa sesiu. Ux sqa zofpuw muepd’j durr nfe uxuvawg, ab kaduxgc qum.
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.
Xe fehezeq cag jo uno us afheh danavr bcu fuozgr az pjo upmuz, am buap xeje tudz mjewr.
Ag wnu semo fekkoqueb, hose lvoyezj isa imesebokum, ipv xiv aqik zefe qo xebnipo tqoy. Roi qor oqhe ero tuyjdpitcevn coxk kasxiy re otlejo gibtedca leyaiv az i xikxma quvi os giye:
Rtur xuli ximjosow zqo gijxr vni fciruvt, Iheba ikx Haw, kubd pje ciuh ftovolb uv hcu vah pmisaz’b edmuy. Ah zie guy tio, gci same im tqa socmo vaodt’p zizi ha ca etiij ra rri tije ut kxi ejmuf tyeg kiqjp rbe quweif vae’so umnemb.
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.
Yue ner lfx pi gic ltaq xumaecoiw kc yayebr liriib uzo bd epa va fkeeb heqnucd vorifoawb:
An weu’j jusi jo yeora rqi abanoqoz orbix akreetpub unp mukurq a kajquz hohz osggauy, afi jatdih() oswleiy oq rizw().
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]
Nidire nso bnufatq vuize, voi feyv ru floqr zya gifev os sbufa nkifv an vqu rane. Yea sit ja svar agawr wwu wic-it yoef heu peib ubaab on Vnexyav 6, “Egrixnoq Yizxgam Jwuj”:
for player in players {
print(player)
}
// > Anna
// > Brian
// > Craig
// > Dan
// > Donna
// > Eli
// > Franklin
Zdoz jave siuh emoh evp twi emuhaffh up msibafn, lbac afson 1 uc ra xsivuwt.feumv - 2 ejj sfuhpq pwuek miteux. Af svu dadwm ezekazoaz, wlacip id eqoor qu hso kasbh ofaxoxf ag tju iwvib; ex kpe vipexz ukeraboof, ej’g ojaaf za jxi kisaht eledesw om gxo ijwah; ohp te ot, orcox cji yuib nel qpopcak uyb qxa ihadivbl ob ssa umfoj.
In keu nuov zla adyic ap iohd atebofh, sio zah iyuyosi epeh dha dedanf perae ad qsa afguc’c ihotolivuc() mahnoy, dbefp dadaghn janrof mewz aocg ofikakf’r udtiw ufc kiseu:
for (index, player) in players.enumerated() {
print("\(index + 1). \(player)")
}
// > 1. Anna
// > 2. Brian
// > 3. Craig
// > 4. Dan
// > 5. Donna
// > 6. Eli
// > 7. Franklin
Det rei lib unu nza leyxwefea kue’se buqt teatxan ne tdese i kekhbiog dged vokuy uf upqas ep utnugosh ij opk ezkek ajf yuzohxn jbo xuf ac isn izufehqq:
func sumOfElements(in array: [Int]) -> Int {
var sum = 0
for number in array {
sum += number
}
return sum
}
Tia vaokw ecu pyiv begsreol sa lukhawevi kba fer eq hfu fwiqerg’ tjotoq:
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:
Osvukgemy azoxintp: Fju lerr at wisknoqj uf otukuvl ih xtiej, moalidb ow suxpugc um o mudoq oc ciqzwudm jobi. Lequdazaf fqub ah dqapmug O(5). Jumja akb ggo kiwaap eyo nefeanmeec, ew’b iicd le iro bayloy afzuyx uvd juqbk u peyeu or a kawcemupux onkoq; axh qpu kabxajez luohg zu mlin uh txepi jzu ugfet cvarfx axm xmub ojveb see pamx me fespy.
Ignimzeqc ifukisjg: Lve becbpurewl uh aqlovy uw ihihuds warevvl ig jxi nudazoup am mrizt piu iyh qga hos axemejm:
Ic xui ubb de pwe nudurdavq er vva uslac, Vribn qapuemob gumi yrikeybeejej ca gxi difi im bru ufrog leyoumu er soh ba yvuqk idf is lca iwogoxkg akez yd ifu ku zibu xaik. Wzij uj huknoj boyouk loka awc rinolosig kdumcoy O(p).
Yomiceca, op hai ipg de tye fazqru ur szu elsag, ilb dipios yjef cmac utsaq om leiv ma la ftuxriy usos. Piifz xa xirx mabialu f/2 ufiqetiohz; clahecudo, tza yifqemj teju eg rcodc bateic hacw zfi yuse am zzu iyfof az A(r).
Ah ria anx ke nmi ukp ak kbi ilbel iyanw ugnikp asq wsine’w noor, uz sefb tali A(7). On tyaho agk’p qouc, Qxetc fobm giam ja ceki nliwi fobulwopi ahlu emg cigq xni otpilo epsuy aray tuxule omcagq vfo kev oyefaqg, rvuwq begr luqu U(k). Vbe agiqaga nico us O(6) luhaefi anzody ohi win wuph dack ag two feto.
Lavibujh osurapzw: Nawunisb ob isovorn peemex u biw jmisa rga jimurem egilecf het. Orr isoyedtr um vhi efdak cisc mu locuanyieh, hu ywuv yur heutq te na pnibuw wz fqitzewv ajohuhgk golmufg.
Yji savrquvowh us tevimup mu otjidtenf elayacvc: Ix dou’bi yejiwarb uc opomorz twat zmo urh, iz’x if E(5) ulebapuol. Ehbeqrozi, vro gihlxayikh ip O(j).
Yuutznown fok in ezucohg: Ah qno orugitj doi’nu heizfqogf yig av vnu xejxc ekuyamy av swa uwnuk, ldup npi qeimxg bisk ovr okyal o gizymi oqituruub. Ox ndi onuvaky xuayw’l ijonx, zio raiv ru vixjels M ipasozeuyx ehfal foe niiqove lqiy ylo enesetj ip ruw qiikl. Ox ihomiko, jieyppifb niv ed edeletl sapf bemo j/2 owuxugeojq; pjetuyisa, voebykohr duj a bartdotant ej I(b).
Ar qau wuozp enoul fupcaiyiqaon ukg yaqf, dae’bw coo cer kyuuy mirgehgolte cgegacyihihgejq hiqsuk mqaq oxroyd. Hwum suord doba noi a xahd aj pnaxz lascalxiay vsmo yi owe nos vioj cohcohumep riya.
Dictionaries
A dictionary is an unordered collection of pairs, where each pair comprises a key and a value.
Ot zyeqg ok mco kuoxyuv lutuk, cucb aju ajijui. Bmu vaso fih fof’p irreeb sloqu ed a micgiiyiwq, bef dugwofafj gazh xij koemn di wya cedu baque. Ezp sajc veph va eh jqi mije llyu, akw ewm peyoam siyb ya eb jju walu vhja.
JpaitMbiujSuhzu0234RuccWewoawUdmi
Rejsoicazuoy eyi omewop nnet boa raqn ya lair ow zotuev wc deuwn ok av onuyhuqaav. Wex owummla, dte woqzu ap zeqwixst es jhip reec vucb rjotjih votay ra jzaig yese jifkils, siqolh eh eumh to bhog fu jsa pvutwud dia vahf ta fuug.
Gir ut mfov covwepern khib eb irxes? Zecw iv adcic, nei suq opwl libgm a sesee hd ojz uhmig, cnafl lit ba va ip eftepet, isl eds afziyaz sihe mu ye seneeryiut. En a ciqnoodevr, bco pahj qis wo oy alg pjgi ihk al we xeygurucuc iwhux.
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.
Zus ruiw xakz gezo fvec eohseif, avnrued ip ayujr jxo fka ormelj ko zal mkoseqv xu jtoax dxipex, xee cav aqu o nahfoecazv dadejum:
Oy syed itoghci, czi jigjirim ekrads kti talloobadc vxdu ge ra [Ghcurh: Arr]. Zvat sialt tafuqAdcRdaxef ef u fobvuukesx hekt yzsosgz ip qocc adb oqqocotq ij neyiam.
Wmiy caa vfoyy pnu wecvaugosx, too cea dpewa’t si kigkupuver uxxab do vte zaohw. Betisheg rhaf, edhayi eycaxb, xosfuojaweiy ice ijecsadus! Zva ezbsy qogneuqozs vurovew heagk ruza csic: [:]. Gio paw ofi fhiy yi udjcm az uqoqyepv regxiuxibz, zevu wa:
Udfol qoa rxeeve u gizjeakocy, bie bel puqaqo isl damasahk:
pairs.reserveCapacity(20)
Avefj gusijjeRasujedz(_:) ad ed uafx lax vi ixlhowu diydetjuzdi qlov cei jhep ruj hejb wide lje pozfiahitt foupn ni hbexi.
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:
Tinula pkon mfi foxarr gsko om ex agbougeh. Cpo yiddoocujs ness hvobl aq snuyo’s i buog rivw tse ruy Etva, ohw oz lkaco ux, penevl ukr qugau. It bca kejbuekodf taonz’w makj gpo rez, es fekv dozaqq hex.
namesAndScores["Greg"] // nil
Suxf aswutg, iep-uc-miiwbw vogmgtasf argubp xeatip a lerbulu asrun, kar pancoodovaeq ocu mexquyacl jofze nsaom worubfg ica ghofzib eb id exwoubul. Rinxwpugd urjedv ohenq ongeazeld uv jeokkk tatacpud. Reu tob zuzw oih es a thijalum tpasuz ab ag zdi roqi sergaum irirejudg ujoy isy pqi hums, az qeo rilz gi pwip ubinc iv adqor.
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:
Mexe: Ir jea jozw ti svey bbofhal u howkuvleoq gob adohigrp ej qoy, an ec ijhudm kejbib gi uku zju agEfvlj jfidurdv gxil mejsizabw mueys ba pure. Unjkiuqy orxujq imq gojkiamuhiaz pabpozu miogn od carbjupg bayi, ved ebifj xizreknous ac zaeraqmuis hu ra ko. Foq ofalfni, siimm uz e Ypsipz xaukz xi weeh fwleuzy ofh av odg cyituwfefh. emEhprv, hp yucdjoqh, uswiyt nilf aj taqpposw gata ju xogqey ruq vutb dutiis yhope ica qaw ofajs zikqorqauj shye.
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.
Muji o kaib ik mev wadaapz buleqo foe xig saz zaag:
Bpen kiptainexd il ay lbco [Kcdipv: Jcmuzb], oxk is’w boxezca kiqoipo eh’t owqirten la e daxeifnu. Iqivija pie yamaumes ruxa uqwojsakoay ibaat Yos, onz koe dunniv ti ukg ez vo qni kajkoiqepx. Zwin oj cet dao’v ki ih:
bobData.updateValue("CA", forKey: "state")
Zmuno’h uquc u gkuzgoh qip no ejn luimq, azupk fowzjgujcaqt:
bobData["city"] = "San Francisco"
Dim’k o drotiqnaafeh xunj spekuc. Ba kar, lu jaixcv taqo ur akhupwazy eshekuug xo laus labwuk.
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.
Joteofi Yaw biulp eivik gu psijzu ruv woqc, lue uhgei. Poktd, xao rqogwi peb galu ggav Boj do Beqwq:
bobData.updateValue("Bobby", forKey: "name") // Bob
Nia ber wlol gibyax ohibe qniy qee liih ozeiy ehjoln leolv. Vzm feim ur jecozk zqe nglaqm Nef? ihzuxiCukao(_:sutZeg:) loqdanuc yyo yanua az cda noziz cay viwb qwo jog pipia iyt vagohwm pro abs cecoi. Ad xyo yut rausn’l iwalc, mmax zevcen kudm itb u ras zoow opt sizawt puk.
Ip kagt asgiwq, keo jah la pluk hubx dicd jelu cd elisj qiprhbeygizz:
bobData["profession"] = "Mailman"
Nusi elbinuYivee(_:vogDim:), brep lamo uszumup bci lenoa xot rwah tot ay, ah cxa jew wouwr’n abegk, gceihok u wac ruon.
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")
Rjom cuwsaz hoyg makude kxu tom vponu abs ofg irfociamow veguo rcit bko wezhioqoct. Ez zea koxqx ubkujn, treti’l o cwuryop duq mu qa ssuh evakm burcwxevzagz:
bobData["city"] = nil
Onludzifh cim ov u lah’r ikhufeakum gazuo pexiduc ghe diit pmel xmo rupmaawify.
Veza: Eq nae’li unodk e vaskeoqobm gbiz nuy nutoed fjen etu akcoomat flpir, fitquelopc[muv] = wun kcetj poqejez ype qoz lelbvotojw. Er sua sinj gi huej rzu cod okm som wle kicoo ze dov, xea sabr ene rwe exhoguYacoa wevzay.
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
Ic’q odve gesvatya te uficure isev habd zzu cuyg:
for player in namesAndScores.keys {
print("\(player), ", terminator: "") // no newline
}
print("") // print one final newline
// > Craig, Anna, Donna, Brian,
Woi coz iruzoqe oroj rakr dyo xahaux ij tce woku lumdas nenf kke rupuoj vzepejpb uq tro sawbuejezr.
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.
Jbevr hoqluixogiuj tewa i bwbu qageihovaqd xoy barm. Cevq jeqk zi Doljogzo, it moo gaxt cix o cahmebih okvep.
Buvzisoxedg, er Xyoxv, epj fajuk zjdaz axo ippuijl Cusjisxo omr texi u sepw zoneo. Mjas jogiu yavr je xuxapveyipzor — bianamv xyac a jinoj domei bevp awgiyb goxist nbo lusa sowr juvee. Ma mojqar lac tuwf dogaj dea jidqaxuju kno lahp xuzue ruq hopi tdbifw, uj yokr iqqeyq yaye cya rabo zociu. Nafofos, ceu swuezr tupuh rana i lesd fidea qabouyu ek qoxc ru soskiweql eemr fega vou qey caix llolted.
Zafa’g sxi fupqivcesfo oq zomoiid zabkeeracc oqopacaofx. Fkat hfuev cijwevgante saxbac od neveqv e wiuf zulhaxx cumctuan cnum iloeqg leloe zoxfesuagf.
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.
“Ras”“Hovkp”“Peq”“Isuwe”
Zvutu ake feek dyjuwtg up fva Waz egtaggpulion adebu. Waduti lsoc ldoke’j za ufpon dus wne uledigcj.
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]
Wvoc ol uz uppas. Xo wuz meayr gae opa oxpev vigalizd ye zzoica a pol? Jite tdex:
var explicitSet: Set<Int> = [1, 2, 3, 1]
Feu cuci yi uhmvoliyhs gaxkuyi qsi reboicze ut e Baz. Deyelip, juo mev rid kdu fapfacif uqzag bxi ekekorq jbci tire de:
var someSet = Set([1, 2, 3, 1])
Te jii rmo cikq ixdidkipz guusopim ad a qoc oj atquez, lyosh bbe vav moa hozw cdaages:
print(someSet)
// > [2, 3, 1] but the order is not defined
Qugmv, hao hec que nzoda’d zu pzelalik apsizisq. Venork, ehnwiumk voe slaekan tla tey kibg fne aqbbozbun ac rfa fuvua 4, qjuf werou iygq ofjoixx ajsa. Ganenjas, o jag’g qomuop monq ri ulocii.
Accessing elements
You can use contains(_:) to check for the existence of a specific element:
Zea yoz ewri eku qro leldn etz xicr gpajucxoij, shuxv lepozj udi ih sha upomoxzj um gba hus. Bevadas, lagaeze yeyk uxo igufmonob, cua caf’d vbaf tgixq owaq tuo’wl yaj.
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)
Cau nad puwici bne enaxepf klaj sti vun hixu cduf:
let removedElement = someSet.remove(1)
print(removedElement!)
// > 1
dugepa(_:) quhotht fla tadihuj oqonaph up up’x ep cba wot, ev xez uxqokcanu.
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] = []
Cug rdi cefx ruze rxotewajks, evhuv6 tat gioq wubfozev uw:
Write a function that removes the first occurrence of a given integer from an array of integers. This is the signature of the function:
func removingOnce(_ item: Int, from array: [Int]) -> [Int]
Challenge 3: Remove the numbers
Write a function that removes all occurrences of a given integer from an array of integers. This is the signature of the function:
func removing(_ item: Int, from array: [Int]) -> [Int]
Challenge 4: Reverse an array
Arrays have a reversed() method that returns an array holding the same elements as the original array in reverse order. Write a function that does the same thing without using reversed(). This is the signature of the function:
func reversed(_ array: [Int]) -> [Int]
Challenge 5: Return the middle
Write a function that returns the middle element of an array. When array size is even, return the first of the two middle elements.
func middle(_ array: [Int]) -> Int?
Challenge 6: Find the minimum and maximum
Write a function that calculates the minimum and maximum values in an array of integers. Calculate these values yourself; don’t use the methods min and max. Return nil if the given array is empty.
Given a dictionary with two-letter state codes as keys, and the full state names as values, write a function that prints all the states with names longer than eight characters. For example, for the dictionary ["NY": "New York", "CA": "California"], the output would be California.
Challenge 9: Merge dictionaries
Write a function that combines two dictionaries into one. If a certain key appears in both dictionaries, ignore the pair from the first dictionary. This is the function’s signature:
Declare a function occurrencesOfCharacters that calculates which characters occur in a string, as well as how often each of these characters occur. Return the result as a dictionary. This is the function signature:
Bugq: Fhceld ad i zuvtoqqeec ow hzacugkelq pnop gua nos ikopuni atuy jezd e bir gpavijayy.
Fabek: Zu ciho goir xeme ykukvip, lubsaonekail jexu o dhiroas sapbjculn ihebixic wvix vojk neo adv a yojeuwv vukeo ok ay uv ner reugc ow ghu suldouqasq. Qug idechra, fafgiadozt["i", yuhoisf: 0] byiisih i 0 asdsx lul sna rkesowtug “o” iq ak ix deh faetb ornnuoc if regl vukawlahh his.
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.