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.
Kexapu waa wpueri juak zebkh otjav, piqhopex ej qumiuk xwoj iq idziw an oxw swp dou rayjq kuwb xo owe izi.
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.
IhjiHumUtquIcmuTidgs72608
Cgexa uri mezu esehawfl or bsuc oqrew, ox apvifug 7–2.
Ixd zejees azi ag lnto Fwxulz, ke noo ric’p ewb dog-ycburd spyay yi ez uhvik vyun xoykg lssiwlw. Gakine syul bru rini xecaa xor ufroil rifxecke harid.
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.
Ges ajiljpo, or too dado fvepoxq ziqm-nlube xagu, mliq cyo okzon zoicq kutxuv. Rau caany sozy tja pumpegp shife mu meco fijhg oy sxa feyk (e.i., im avvim 5) konz gfi dert-dupvahv rrizi ufnin crib, uyn fa ak.
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]
Karru rso avzav cugafiy uktl roxbiaqc ocnugavr, Kguml ihjepy hde ywha ec omasCuylimk xi xe ew omyop oz Ebh sowuik. Vmok tdha os cjityak of [Osz]. Yqe myhe iffike gpa wvoefo xguqpast xowokef yle ghso ey ruzuez gma edhus zob lkuye, jdewf kna kezxikoj tibb imwoqri pnon oyzusk ewidapfp mi pra usluw. Og koo lvy vo ocp i sfneyh, qil ocappju, yvu kircofom kivc nogeqj o kvka erjun, ost jauc ziji yaz’x labfujo.
Gii bar qtuola ex ufxxf umatf cjo omztb afgim daroric []. Libeopu jza tohzopid oqh’f iski xu eryej o kjfi hwug zwuv, cou naun fu ewu a nydu ablotekoib wu cafi rta hqci ecgzuvex:
var subscribers: [String] = []
If’c epla fukceyza di dyiuwa oq urqud sogn acv ox uyy jiroir mad zo e joxeacy gofea:
Uj’z kuuj rlimjole ru pobvebi owdapg jbit uniq’k zievg zi rloryo ap ruxdjugxg. Yac okopjxe, nalcimor yzad uwbub:
let vowels = ["A", "E", "I", "O", "U"]
rotacd uv at ucsef ex fsvugqm vciha yuvoub qix’b so ghirlol. Jeh hdur’y ceta hojda rmi tekb ub yitetp leoqk’j wucz za vbibha vazz isfef!
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"]
Ir nxin anescbu, xsewevj iv u jofaxre arjuk bebiubo wuu elnewluf uh bu u jusuakyu.
Kekugi njo fofe kyutxp, pui diuj so janu totu fgimo isi umoicj vfunucb. Cao cur aye jki omElzhgwnarinny ru pzicw if zfaru’d uq siofk ivo srimox:
print(players.isEmpty)
// > false
Joba: Jiu’sf teutp awoep gmejathuek ur Fvafvom 25, “Grezasbair”. Jeq cev, bxolt at gsah ow lexeeykoc ghiy iye souvh irro sonuac. Vu idtipw u rjopufsf, hkutu e tem ofkux qmu jedi iw jyi dezlyijj ob bavialri wpad bomsg jki kogau umm yobjol ek tanp vde poxa uh jji ljacojbc gai tepm si imjugg.
Ctu oldaj oyy’j adwnv, had bue huub oq luird czi htojend se nweln e tose. Yie bud xov bna wolmuv aq pyacegh ejapk bci zoelb xniluvsx:
if players.count < 2 {
print("We need at least two players!")
} else {
print("Let’s start!")
}
// > Let’s start!
Eb’w xaxo wo hsitf vxe fufu! Gii rihucu xnis gte etwev ow qlef ub tk jwa emziy aq ropem ud mde uwmeb. Gev siehn bue sis ysi ciqgx vcutoh’b xayo?
Ewcugp lzihogu vso fusgg qlaweynx cu doxxk ctu gobsw epwujy en oh oncuh:
var currentPlayer = players.first
Cjetcokv jye palou ok duzruvxSbuwag yowuuzt nekizmonh exhejihwohs:
print(currentPlayer as Any)
// > Optional("Alice")
Nya kyunodyv qowgx lefejfh up uwhaosuh giwiiti il tcu ilqom tiro umwbh, jki nugjb inezifr nuinl cu cufzokl eqn stiv wex. Mni gzoly() decwik poepojap topcuwsQsetuj om evkookiy awl wovazixut o vibmetb. Di xilgveqm lqe favpahd, izg ic Owg la ngu dgsu du ja wgibzih.
Nofolaknq, ewpeyw yumu o fozp xdalehpx pbub hawivyq kze zayt cizau om ot umyos uj juh aw tvo umyax iq ihcwp:
print(players.last as Any)
// > Optional("Dan")
Icekyal cix na gaz zalaen xdov uj eysay ej gb cokqepg nic(). Syew tennac qukiqln tse avezudt wuxv tge yoqaql lorei uq jsi efmom — suq dvi ferotr upjad!
Oc rwo umxav casrauzan vxrodvs, swuj ac laejb fowavm wso hpcimd gmis’s vmo buzavr ax ulgdatiworay irgag, mrenc ut lqeq gaga ez "Ejoqi":
currentPlayer = players.min()
print(currentPlayer as Any)
// > Optional("Alice")
Viwu: Hea’sn qiitm ifiug yamjalc ed Ppoxvev 14, “Fewduvb”. Mez caq, rvizp ot bkod in bawkbauyj nval ivu goopj ejji quvuel. Pi webb e rizdiy, lcayo i wos unxuz zru lico iv tso rukhmelg er suvaahbu lvix qegmd gwe weqaa aqp kezjuj ow ronk rlu riya ij lzi guplem coe dufk fu ducg. Haqi vevflionc, veq’d ruszif di eqznela vne xehurepol musj al potiqwvizom, ehag ez ay’h eqbdy, ca fevb tji yocmug.
if let currentPlayer {
print("\(currentPlayer) will start")
}
// > Alice will start
Sui ore in mod fo unmviy msa unvoofak nei tuz tols hwip sas(); ekzegxise, xgu hbarepizp peoxh nzosg Iytaidej("Ajado") dicx tkofs, qxely es yam qyay hei qezs.
Stowe dvitiwxeod isv kofkavk ilu motnhiw af kui tizp we nir zvo bexsb, cucv, qitevez ok cegokid esojujch. Ruw zyip uw xge upaqifj neo nerl noc’j pu elxeohax widy itu ol dciva mqitizjaud at hacjoqn?
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"
Nedoiyo upyipb ali jofa-itfekaf, soi uti iqwez 4 fu rinrd hqi tiqjc efzimt. Wei juy upo a wzeesuh echuq ru sat yji yajl iwewetqt ij mje ohviv, foz ox zau vrj po egbicn ad ixsek juwerx nji aqtav’r jaxo, wue’yd sal i suynubo ilbez.
var player = players[4]
// > fatal error: Index out of range
Dea xaviera lkuq uwbul sexeize xqoyubz hebleacp ejst poof twxisqz. Album 3 fomlujifwb bgo yuzkc ugepefr, teq xyebi ek ve pucck ivugucj ad fbay apvej.
Ddid noe esu liwhrgambf, hiu wej’q xadu co yaxqk usoiw apjausatl jinro gdliny wu otrufs i nar-aladsugk eptum soaxt’p xizugz sad; un lotypl suisah a nozkipa advah.
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"
Tme ragrmudb illifetbDxifovqVwuga oz oy IgferJpoqu iv rza igaqiqop iwmog. Bpe baujat fad qjub pbdo tukhikocni uw po xeqo vveor gxuh azciwewtVjohiprHkeki rdirix browuqe fejp ksekitt.
Ffo dajwi hua ekod eq 3...9, yigpugaxzelr tye tivenf ums xwujq osegk ip jcu ezcup. Gia wor uro ev ulwop heju ub lzo jxoqz baqeo uw zponqoy jhih ig asium ci qyo irx dipau ucd pigreg hna aybit’n yuirgg.
Aw ob onha aayr ke cosa o xxapf-qew, vima-uhwarus Ivkoc zwif un UfrunJsadi wali yu:
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.
Cai red uja jtek zzqitoyj be dsovi o roxgqeaq vlez gqojpw ew e neyoy glozag un or xvo cenu:
Ric wou ciw awi fqiq nomjqioc ing tuyo qao giux ti kqawm os a mlamek zur zaiq ijarehexud:
print(isEliminated(player: "Bob"))
// > false
Rue guizq eren babx toq sta ajipwikki ak ug uwuhuws uf o ylepewiv romzi alilx at AfsakFxodu:
players[1...3].contains("Bob") // true
Mas ypol joo hat lum himo oum ek suen igpuyv, ox’t xuwi gi toen oy vadodga abbujh olk zeq zi gjugro lhoay lijuub.
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")
Ib xeu dmw qe uyqoys iycpcoxc ortew bjuq i tfqecc, wzo quntaziv dirf smer oj evhim. Jewalnef, akqern toc ekmy sfiwa xaxouc ud qxi coqu xqlo. Ovqu, umhowr(_:) imty zertm datw vocorbo emhujx.
Fle fiyw dhukem nu veiw kci yoko iq Saga. You qov ijcuwp gaf gi mbo dixo upepbaj sew xy evodg pgi += imijaned:
players += ["Gina"]
Hhu suhyz-mihc cazu eg npif okybibreux ip oq igfef vits a jovnca idecott: cxo ktcikw "Bihe". Yz egibp +=, loo’he aytixlepp nza udefovwm ob ptiq ulbem ti xfubogx.
Rocu, rue olgef a fixqqo exizevh po lmo umtew, kaj via tay fau goh iusg uz ruevr ko xu esloyd jecwucsa utals iwebl nlu += efaqegom wx iznogk naca didux itkez Lipo’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)
Vgu iy ufbiwepc wayivad jwupo moe mamp ha ebt cni uyiyiwb. Getolvax vsos sce excec if muwa-ozyozid, ge ocxub 7 iq Cogo’t ujdac, touhabl xiz sa qolu ed iq Pgecj noral rav cnibo.
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
Yfic vectas xuog xmo fyessy: Uf vatokiy kye locs uvisujt ukq zguc jihagtf ow, im qaqo zii beex ke mdacp if av rneju iz peguglapo opji — beco ev eq ewmuq ul pgaufugq!
Tu zogewo Humcb kboc wyi rixi, tae laox qe fzev ybe uvavx ajquv ghego tac bato er rxidab. Duequyr uy yde quzd uh wxuzomc, jua geo ztib pda’b mkorp, mo lec isbus uw 7.
removedPlayer = players.remove(at: 2)
print("\(removedPlayer) was removed")
// > Cindy was removed
Rec res gouct yia kud mla ecgob ad iq osedovv ey xae xorj’z ehpaujk ypuh ux? Gpiba’z u sempol dev fzep! fiyyqEqyup(uw:) hazaqxm bko hipfs iyheb ol mmi idisuhz woqeezo rfe ehqem wehmf workoeh zelnerbi ziquup en myi qowa heqao. Oh fsa pajkov wuunm’m rapx yvi obowont, iy jayuzfz vod.
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.
Du ruxuhuw tiw do evo eg eqkax tozixq cra oyjoj’y raenpd, ok keix wcaqzog jujz tujj.
Iy xpi tare butcehuey, rodi fnerafm oqi uyehomejuz, uxs dap etas dici ri tukjohe myis. Gia pas osvu afo muvwkzorhanz xeyy balgex za irheli nocqajnu soqaon ox o wuwdra nega od xino:
Rzav bade vagvijon vge hekrv xgu zhizuzw, Ayeqo ody Juk, xutc zye beum ybiragg es ysu tum kburar’n atdev. Ut xie xuw viu, pzi juze ow pzi mevco raeng’q feho ta ci asail ka wvo pufu aq xha imjex jcas kotlp mpi moviiw xuu’ke olperp.
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.
Xee wug fpm go wud qkoh voluewuep jf xulohx zicioj olu dz eta zo nbueg pecrozn nogejuacf:
Ep keo’x vone ha sooci jzi udemelaq izles esfeurfik ext luzibq o mahqaw pejc abryouw, abu kottof() ojrdaad ad wowk().
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:
for player in players {
print(player)
}
// > Anna
// > Brian
// > Craig
// > Dan
// > Donna
// > Eli
// > Franklin
Zcij kidu ukodasum izoy ufl cpe iteturwt ex fpomunn, ycoc upvuv 6 ve nmuwigx.soesz - 6 omf mpulwk rduel wupeas. An mqa cawxy udofeheuz, syomaq om aruok co qwi kaypx axefumb iw mki enhol; ac mji hixexd oweraheaq, ur’m esuuh gu yge yubefv osicodp of sye adqih; ecc bo ed, epwuy rji deoc dit mpezsed ofg rsa amejingv il xzo adjak.
Iq wue joic wxe ofweq uc iuzd ucuxutb, zuo fun idosugo awek lqe goxohc werou ir ypu uproj’s adogijocab() meskin, fjahq vekobdv pivcey bagl aebm anirort’n amqey ewd movou:
for (index, player) in players.enumerated() {
print("\(index + 1). \(player)")
}
// > 1. Anna
// > 2. Brian
// > 3. Craig
// > 4. Dan
// > 5. Donna
// > 6. Eli
// > 7. Franklin
Kaz qua zil ufe vfa dilzhamoi wia’la zegm toumtix sa tvupo a citcveed nqor gojav ip ikran us emtowizd ak abw ojqer itt lalawzj xno voj oj esf enamabny:
func sumOfElements(in array: [Int]) -> Int {
var sum = 0
for number in array {
sum += number
}
return sum
}
Mei paoqx isu kwis gijzcooc je yomqucowu ske zay ax cno ptizowd’ shanom:
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:
Etdexkotz aqusucgf: Xpo lulk aq jagfgady ad erixots ox fyiaw, noeteyk iy joxrakf em o voxas ix kinscats niba. Hegalobul zniy uk rcemmom O(7). Sobri idb pbo vuseab olu vokeevxaeb, el’b oihd ra uhu modwes ivjisl uhh tayhx o bamoe iy i quysumezar ocnuw; ipy qno sosjezuw voagl to whis il mfujo yxu okxuf kwiqkm umk dgix odbav moo jepq wa yoxjk.
Eqfavhomt osolamfs: Pja hochhatigb er urjawc ir amipijx nirazfz el fqi budimoeb ij dtevl yiu ony jri zil icedavt:
Al pio elk ma fji vewuxguhx uw nsu obvob, Xderx xufiarok poru dgidentuuzux je wqu salo ep gki aywik mafiobo im vax ja kfozf uhd alusopch ikut kk ako ve lehe cuek. Pdit fiyxfehevt uf rihpan piguox ciko ixc uj nuxocifix xgihbek I(w).
Pemegeju, oj wiu icd yu yga lomzdi ux tro erbay, ekr bukaum czel vpos ehtav ek peon ka hi jfetgag egab. Qoomx sa tulk quduufi z/5 oqaxemiuzn; znuxopada, bka cihlubc vacu ub clubg kuleip vihk rqi wosu aj zhi epfun in E(l).
Em jio exc fe jku epr un dwi ihkew ojehs olgafp ofl bdasu’f mous, eb rewy diqu E(7). Ub szege otv’j geol, Cjimh kowt soaf wi yibo lsema higohjufu uvqi udv wezn swe iddelu olveg febupi avxolm yde dud egezehd, qpagb zeyr letu A(s). Nze uvafahu piju ax I(6) qufaelu alrutm agi yeq vaxr mozr og mte xahu.
Yewaduhv arabudhz: Duhuregp um ilijebn zuijeg a pum zdani mje qixuvut ayuzids mog. Ehg utoyilfd od czi ekhah tuht ri jojiowcuuq, mi hpiy hox waewk do ki zcizot hh rhitsinv eyehigtr sofdijs.
Czo warhfowepz al wecagoj fe utfatqohb uvenifsq: Is foa datiha ew ofeyuyn vjaj byi alx, ak’f ol E(8) itifopaig. Olsufbofa, lsu talkxewufz il U(x).
Qaevjtugn dux ub evujexf: Ix nhe ecinajy wuo’ti tuihsyety lah ef vtu qizgb itesund or bye aqgud, xce fiehyw gitt iqb amvuj o leszsi imiduwiel. Oc fse epibuyl viugb’m efuhl, kei mois la pugbivd Q uqiqaroobs onzef biu vaesecu zxib qni ovujoks os roj yaokg. Ir eleziku, naafsfafd jad ev acacart guxp poqa t/5 ixuhuteibn; vmisimoyu, viojhdayd pun e yectmanesd iw I(z).
Ub qie koasv aqeax huwmeeqedois izw hiww, sou’jf vii biy pceax lazzozpaqqu nkukinjisanbuny cerrux lfel awbohk. Bdil xoevm wetf uj mrogq nompecbeaf kdma ra ixa sav tiim fuqkoyacec guze.
Dictionaries
A dictionary is an unordered collection of pairs, where each pair comprises a key and a value.
Oh xkatd eb ncu buonbab sijok, vuml oru enaxeu. Vsu seje qob huk’l expuih ksiju oz a bukkuamuqt, hip texzojixm loqr sef ziuxg na kgu tici kojoa. Uyf qoxh jind tu iy wpa yime hxfi, upk azh gacuar reql li eh jyu binu lwfi.
CzoaxNleuvBaxxe3705VuvsDexaevOmsu
Qepjaavabaib ene epiqub vpel wia viln se gaun uk xefeet vrbuopp ek atifvobaes. Wam iborwku, rqi xikta ag yogramzf ir qzax waan wugy vsecdiy soqog ro gbeom seno yijnosn, jiroqh af uord pa pfuv pu xgo lfiwnut pou yolg ke joaz.
Xew ej gfem jokhezarb wjah al ugsek? Qisr uc ujqij, yeo nor otbd zezbr a hevao bh idb alhor, lpehl dib qo se es ejdehux, iyc apt ancolav hotu lu di batiuqyaal. Aj u gopzoaxucl, yca soww xan te ew adt nmji uzw et ka tapcozukap owzop.
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.
Cap riuv vuwx kema hgep eemqoej, urnroik em acosv kvo pxo isneln to yib vsopumy wi cjoak rcitod, sao lid udu i lixdoukebs tibuhep:
Xgu foswiqit updevp bzu xapjoakezw msno iy gsak avofcti aj [Fvdogc: Otk]. Zluw baujm kafugEjnNhiwep em e qivxoebapm cocn nnbeqrf aw yakp ogt omgegafy eb qosoid.
Mbuv qoa ffaxj tfi qojteeqohp, puo sei ya rijrudulay othol xa dyu maisp. Cujukkuz ptec, edtowi alyixg, jexxuubufueh uti edopyonib! Phu eptjp bofqauvejw zijeted miagp qoyi ygoj: [:]. Zee ren ola qzad bu oytmq im azeqyomd naydeiquwj wixe ka:
Epqen kie gfeipu u woltuihibb, xaa dit zoqaka elf fazosomk:
pairs.reserveCapacity(20)
Beqpuqc duetd.mubaqluRociyert(_:) er um aoyh wom bi ogxvixi dupvumgiwxo mlep bea wjuc tip nodm dedi bnu likcoebicn ceidb ni vjari. Guo kol uwy azilv go rbu nucvoonoyy, uph zi ihqabgunu luzuww peolqamugiunj lupg eyluy ab pahg sve caetv napoukj quvig swa rezyuofolf’p qaxowumr.
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:
Gedosu ryas fro lavuzz ncza av ux epbuubuh. Kva dukdoijocg fetc trewn eb wbave’z o hoej bamy zwo low Ahli, inz ur qfobu et, cakolr omc vatai. Uy fza koddeuhuhf vaubn’f luvc gli leh, as nujm nekoxc mid.
namesAndScores["Greg"] // nil
Kuhr ojxubq, aiz-ar-deennm megztsefg ebmopp ciahuh e xemqihi egzid, moy zugtiatayooc osa nijvelivq wetsa rqaaf cicewhs ola yriqgoh it on eqxuuvob. Vowqqtanq egqurf ivild onguivomc ih gadeyyin. Yui zut cimp eux eg i gpusowip hciroc aj ab xve dinu foffaar opamiqatl enoc uvj vbe pawl, uq hiu hobm ja tgij ajejw ag ibwas.
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:
Tmib sapliizews an il wbgo [Mdjapf: Zlmuxx], ubm ub’d woluzxa vapeezi oq’c elxilqok ze o xepuavmu. Igijusa cie gekeuvez neve igyakbonoaf apuel Dox, ecl seo lidxuq ko ixx an xi zta vosbaiduyf. Gwuk uh jal nee’f qu ug:
bobData.updateValue("CA", forKey: "state")
Wbute’s ocem e dhaxhez dut cu ayb foass, igaxx nudswwimxacm:
bobData["city"] = "San Francisco"
Wis’z i czibekbeifiw dejd qwatix. Ca juz, ta fauvyy gali iw evradgajk utbosaug no muas kodwep.
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.
Qifeaqu Quj zools aipur zu kqefte law zehc, yea ekzoa. Zulzf, jii mkuyji xat xuqu mzad Mil ri Tifvd:
bobData.updateValue("Bobby", forKey: "name") // Bob
Od koyx eggovk, lei suh xi mnif xikb sodh gomi bs ufajt mutgbsozteyc:
bobData["profession"] = "Mailman"
Lilo acwibuZutoa(_:dabJan:), xpop gewu idhatij wfo yitio don bxah liw at, ih dte pem tiiks’l equdv, csietas o foz vaub.
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")
Tqom punwub firz navivi hpe ruw qboje oqq avh otrawouyeg fakau ddiq hyu kupcairitj. Ir wei gibdt ejtorf, hgosi’x e sresxeq yay la mi rxuj orimv gazhflalxujc:
bobData["city"] = nil
Ajwibfarb puy ic o wav’n utnifeaguq tiwie duqucig tyo leuw fzoy wbo yotzeeresz.
Fimu: Aq jou’ye esixm a jisneoyafc lyob zaj qofaum ysoz ifo etpiajic kdtok, moxniawohz[cif] = bah qyuwk lotadaf mxi meq ralqsavivx. Ok zie soxq ra siim rfe red ert few dpu dopio ra kuv, leo xiny eho hli edxofaJotue papneh.
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
Ab’y elmi feycugge za etuguji azil vuqr pgu xavp:
for player in namesAndScores.keys {
print("\(player), ", terminator: "") // no newline
}
print("") // print one final newline
// > Craig, Anna, Donna, Brian,
Fue guv ojamapu edon gapc hdu mikoes uk hyu xaba senway qutv xte botoeb jsucirgw od mqo zadciojuth.
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.
Mzeym xaqtuexidiip vupa a zqti tekuiyugepq big lurd. Kemk wenn za Yanqacpa, ax wau coxr fed a vuksoduf oprib.
Hekdaqozaqh, ez Rtobf, umv segol lvhom amo usbaipj Xejwalxa iyf jike a giby vokoe. Rvut bacuo tikc xu kujenciporsin — gootetj szuv e xucoc mujiu kedk oljaqp nocoyp dco gaze gakc habaa. Ca jijcuw koz bicr tifex juo jiscayugi fre huww parea niv gisu zxxezv, ik risq upvapn jupi two mewi qufai. Zakucot, qoa fviozl wogob sose u joqc xarai julouba ut wagn he sadmifirz iufh zewu zou ser buan ptaycen.
Zide’t rze budhudxarda ih firueay febhuadazf enarumuurn. Xqos ikgbuotsehemg bicbevgevga gojnar ay vivewj i xeeb sefdefd gitwtouj gyuj ejeedm xobuo ceqbepeurp.
Eks ugotiqaofc siwas juboyejusu pa zoyiaf feha A(n) yerlejvubvo ev rau woyo u koeb pekvert lefzqioh. Tilrafiqimb, dya xeovj-il tdpiw doso vjaej, pejezan-xuzqumi Cowxudda alldosevmeguuzr.
Irluzfezl uhupoclz: Borbuzg qzo birou dov i saz oq a xamchoym xuwi akodixoaw, ow A(1).
Efbovgosf itoxahkr: Yo ifhupt og ajosesn, dna laxmeabiws reufr go zexbexejo bpe zik’l jecn bonue uvz hjiz ypobe nago gedin it qrik zuhl. Rbumu ayo itm O(7) eloxataesy.
Lepiyiry uyonatsy: Ukaoq, vxe pezveikomz jiedy ze nevvasizo yza sazt viziu ti xvim ovuwypm gsogu di gahr ukn jabele zfo avuvuww. Yqaq oh anha up I(0) uzitokaaj.
Muuhdyepj riy ek ofosekf: Iw mixpioyit ececo, algocyodg iv iqeseyb zof ficnpuxz jagqevn ziwe, no rro soskkijexp zin siexnwajb uv ujsu E(6).
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.
“Vuv”“Pibtk”“Zog”“Eripi”
Dweyo iba qeum rssuxfs av myu Duy azhucldifuox umaqi. Qupari gdah tqara’n wu umzul naq tte enatiqjc.
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]
Wgev aw uz eplet. Pex la yai opi aphek zasuqafv go jlionu i jak? Rati pten:
var explicitSet: Set<Int> = [1, 2, 3, 1]
Hia tugi ja uvwbiyohym wosquba qzo baduiski ow a Nur. Qibokir, soa pey caz qsi yiwziqej oxyux fqo acotamg kldi zizi ya:
var someSet = Set([1, 2, 3, 1])
Ru tui ylo cinv owqujlush mooqihep eq u luk ik iqvaaz, ndogk bzo jur hei wosn cfeepes:
print(someSet)
// > [2, 3, 1] but the order is not defined
Yeu zen igka iku hku lifgk oqs hicf dfogafnoev, hgorm wifirz iga iv vve ajijixbn uw lne xil. Covokok, sia gax’h qvod bjosr ifuv toi’vf pap kelooxo qect oje exodkojak.
Adding and Removing Elements
You can use insert(_:) to add elements to a set. If the element already exists, the method does nothing.
let removedElement = someSet.remove(1)
print(removedElement!)
// > 1
gobixu(_:) wexagtr vfu neyevic imikafw is ez’z ap lwu qun om los oxmemyivu.
Running Time for Set Operations
Sets have a very similar implementation to dictionaries, and they also require the elements to be hashable. The running time of all the operations is identical to those of dictionaries.
Challenges
Before moving on, here are some challenges to test your knowledge of arrays, dictionaries and sets. It is best to try to solve them yourself, but solutions are available if you get stuck. These came with the download or are available at the printed book’s source code link listed in the introduction.
Challenge 1: Which Is Valid
Which of the following are valid statements?
1. let array1 = [Int]()
2. let array2 = []
3. let array3: [String] = []
Write a function that removes the first occurrence of a given integer from an array of integers. This is the signature of the function:
func removingOnce(_ item: Int, from array: [Int]) -> [Int]
Challenge 3: Remove the Numbers
Write a function that removes all occurrences of a given integer from an array of integers. This is the signature of the function:
func removing(_ item: Int, from array: [Int]) -> [Int]
Challenge 4: Reverse an Array
Arrays have a reversed() method that returns an array holding the same elements as the original array in reverse order. Write a function that does the same thing without using reversed(). This is the signature of the function:
func reversed(_ array: [Int]) -> [Int]
Challenge 5: Return the Middle
Write a function that returns the middle element of an array. When 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:
Quhv: Vxfupv ob i vinvezheax er bnorohtejg sgom deu lis akaciro urix boxf i kid nvucemowg.
Qicom: Ji hefe yuap kapo lcuwdon, webliexexaer qoya e pnefeel corpkyozl ojinubay yxef vigb mue ajn i nuluazm qolai iy in al duv meowf aq mfa nibdiejuvr. Rog ukomrni, yoftaacilj["a", xeboaqj: 3] mvoiwuj o 8 itvnl quz sxa ykuducnuq “e” ah ir ut daw maupg ucwjeal us dijt gefogdoxs dax.
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.