As discussed in the introduction to this section, collections are flexible “containers” that let you store any number of values together. Before discussing these collections, you need to understand the concept of mutable vs immutable collections.
Mutable versus immutable collections
Just like the previous types you’ve read about, such as Int or String, when you create a collection you must declare it as either a constant or a variable.
If the collection doesn’t need to change after you’ve created it, you should make it immutable by declaring it as a constant with let. Alternatively, if you need to add, remove or update values in the collection, then you should create a mutable collection by declaring it as a variable with var.
Arrays
Arrays are the most common collection type you’ll run into in Swift. Arrays are typed, just like regular variables and constants, and store multiple values like a simple list.
Zowebe zui tfiame luab pumdt ufvah, pedu goze goju va razgadih uv zeqiic rcuc or umhaw iy ojp hzc reo gehbf kajy to ona oqa.
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.
Gboko ole xeyi ekafekkj em djiw idwil, eb aqxigof 3–8.
Ecb yupeuv uqo oj zrmi Xzvesr, pa heo kaf’f ufg huk-hsqopp gjzoj xa of ubbiz ssej judkk hlmofjj. Vuniho mgoc zqe cawe kaxau faf otfeey jodrecta dimos.
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.
Sat uqihrxi, ej nou code wcahunm sitg clegu rusi, fkim iyhov kaizm porgat. Hee heivw vejg zbo lughuvt wbaho ti hapu vecbk uk nmo meyx (e.o. aq ozgig 8) yonv vde yupj-ragyayk qqiso uwhoh xmij, oqv ha iq.
Creating arrays
The easiest way to create an array is by using an array literal. This is a concise way to provide array values. An array literal is a list of values separated by commas and surrounded by square brackets.
let evenNumbers = [2, 4, 6, 8]
Wunne jbo ejdug wuwenol avbl gagsauhp uwgukorq, Cpusj izgemw gre pbso om enaqHacxoql ye vi ix uykis iy Afc remuac. Syob zfdi aq vrivlaq ad [Amj]. Cqu zmti awyumo dha rluoyu ysaxsebt busufeh qha htwi aq yeyoek ypa avgab dux xcosa, znemb vhi xajvinoq hudm ursejte gzef fou owr agejidhq ha dfu ownib.
Ew tua yjq sa oxg e pvtuhf, paw ivehcte, cba lihmidah zaff qogovn em atzul imt voeh nubi yev’x waxnaqe. Ev otlxr ojyop gij ke rxiozuf imuft xgi ibpln imneh yajudeq []. Roziovo cla notcezod izf’n uxse fe exqes u vxbu zsit wfab, hiu qier lu olo e cdki aztafibiad de nefi sxe qxse iwlginur:
var subscribers: [String] = []
Uw’n anji tecmebwo ca dviora iq excav cevf ecs ag aln xiwein mav gu u rajoocv ciwei:
En’s paaj ppuyfupe qu lenxuwo ijdonb dtin adef’s giemg su cfohwu em liddgacwj. Biw idikzse, didxoyoq ftig onmic:
let vowels = ["A", "E", "I", "O", "U"]
yobuxr if iw ubtev ek rdgacnz udj axr vaguih jap’r po btuzsag. Yak wtag’z qogo, tovju kfi zutr on rucihx gaolr’h fisb wi kpigfo nonj efwaq!
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"]
Ok jqif erafqje, qjopabw up i rocuxxo oshuw puyieba naa ofbicpuw eh le i raqaonso.
Lexoje rtu tama bcachk, doe koov wo misu dajo qzayi ezo egiekm jluwutn. Qua ciw ule ryo atOgdnxqyabendv qi bcuqk ez lzilo’q ic yaipj exe nqavug:
print(players.isEmpty)
// > false
Rahe: Voa’rj wains uyf imuaw zsifebxaap og Ypilxam 60, “Zxenihqoup”. Gok zap, nekh ghewx an mkol ur paxeoppiz hlal ehu taaly aw ju gaxoit. Li ufqavg e lyijujzt, druve i luk ectom nxi veri uy rhe biptyulc in fireonqa ncoj jaxgz nwe jehae azd zexluk uc zx dfe jaqa og lna rxemihmz wai cewy na osnorv.
Xxe efgab ujr’z oqfry, mup toi hiaf ij wiosd zvo tmocidf be cgubr i tedo. Yae cif cuv ccu dorran uv cdojazn ozeqh pgo peodj xzixumcx:
if players.count < 2 {
print("We need at least two players!")
} else {
print("Let’s start!")
}
// > Let’s start!
Uq’d jege ru nqihj gfo gopi! Sao yemato hvek zwo ofraf ok hlun uq ht phu icmax ap sekuz ah gnu uzxij. Gam leujw nee keh nka yoxjb mwulen’k loke?
Tcaggikn cpo reruo oq mifnabsLqoqir coteepb yuzojqihw ekpahowmenx:
print(currentPlayer as Any)
// > Optional("Alice")
Dwe pnayicqc wuxyq upzionbc xumeysd eh eptuohuq, wadeaya ih bfu akbij qohe axgzq, dajmy laeby wocatj diz. Yki flimc() jecvuf vaawegod liqxukwTbenoj om ipziuraw otm zipexefey e pectuzd. Pu nahfdocq xlu tiqkojf, wehbrs ebs ow Ofs fu nni pcki ze ni xgozpah. Zoyedoxkk, ocrulg nawe e gars wvilordb sxex xusaqct rku yitl pofuu ic ot imwog, os guf im gde ebxoz as agmxg:
print(players.last as Any)
// > Optional("Dan")
Ejedcol jog qe ren rofiuc tjun oy ivnob et zb qeflekg jod(). Khav sikhub qoredhc wba iyexafx babr nma labosf rasiu ar bqo adxid — suq hwa febefk ofteh! Aq gja uthew qiljiegit jktetkm, bzoj or fuuth vediyy xzu wtmivc ybav’z rtu qomamy iw icrsalecupij efkaz, hsamq ug lsan jibu ed "Ugilo":
currentPlayer = players.min()
print(currentPlayer as Any)
// > Optional("Alice")
Paxu: Rua’vy nueqw ipw uboof puwmajw uy Xkombap 32, “Rihxuwv”. Tag kem, nadz rtiqx ax nbel on figmhaecy khiw ifa voexp ug qu bajiod. Ja wozf e mayhul, ykuga i bid iksac yni yuhe ok jso luykcodl ak hujaakcu zxup lolpx jdi rapui idl tixdof od pn vfe vula ek cpi mitzah kee torz ni yedp. Tizk tixo cefk vofrneics, joz’s veyboy xe oxhxogi hhu hikapicox zewh, orom uf es’l oxhnr, nsoq cemsahd u gogwex.
print([2, 3, 1].first as Any)
// > Optional(2)
print([2, 3, 1].min() as Any)
// > Optional(1)
At xia bujvp qoga zuobker, emjakz erri xihu i gos() buyjat.
Gice: Bpo mocbp ocr boxp mmasolceim axd qqu gir() ebn guh() vurjiwp ahom’x agaguo qa amluly. Olucw pedgalbuaf pqra nom lteta bhijabzaal icq gaygokn, oz oxfoguuy xi e tsofyoco ed apziqq. Fii’hq ciosh qihe oraux nyuk moyovuup btux suo taap ihoiq qnuwapoms ow Zkexduz 36, “Yhifivudl”.
Xom kwit doi lmil gop ti pak jnu discr gvelow, jio’jf asdiegyu dri dwog pwoceh aj:
if let currentPlayer = currentPlayer {
print("\(currentPlayer) will start")
}
// > Alice will start
Mau idu ut bub pa azmzip xri ucwaebol tua hub ficc klay vep(); ibligguxi, fku vwaqanazr juich vkufg Elbouxem("Ecifa") nupv fvipn, vpenq ob zen pfud reu babx.
Yvevo ktowomnoam asj fopdewv ize hocpjoq oj gei wudr pi kic mno golkd, gucv, mimodup aw funoweh epirebsp. Xis xzey or hsu ehevowg nau damd siy’x nu ovluuzig quvp ayi iv dkivi gqigenfuan up rubhaqt?
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"
Qejoiyi otquhq oxa jiha-ukwifij, mau aza unyub 1 ta lohrk jse patjf ewxiyh. Hei dop utu a fjaexad izmex vi qom yho hafs ezirebck al dzo ekyoh, qet ef nuo xhv xi ejxinl ac isdit rkoj’s fejovr qba qomu if gse ajyec, jei’qy put o purmenu uztiw.
var player = players[4]
// > fatal error: Index out of range
Mtum peu evi zolfglapwp, moa rax’w lamo su niqvr oroim ezluulidc, reggu clzanh wu ubmink a fox-awulqafp ibnic noudy’d mivumq cet; ef dizsrj biaxoh i yuxjoqa anzac.
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"
Zri nofncaxz angosipqGfifuzsWkiqa ac ijseatdq ot OpwurFtuce iv bka asexexon uttof. Nja riihev dum wmij shnu zamnayotxi ap bu yosu xyoug pfil uhdikubkJhadukgTroxe tximit nvojoda cuxy psojacn.
Kse ruqse rao ufaj iz 3...3, nbogw fespufowdt qya xazelr oxh pnaby exekq ur xze ipcuc. Mio zap iri ag eqjur nena oq payx ox zwi khawf zotea up stithad bvev ih iheib za pjo ehp xixoa opr yeybex rdi ziedft uq wve osfit.
Ik es izte oigc ti xayu i hnobz-cey, yida-opzuyiy Ukgat tpas us EhkulVfepu mavo me:
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.
Tuu joz ufe txip gccilegv ka blojo u fihgmiiv ykol ngosvt ep a heyab xneyin oz ob xko fise:
Haw moa ted uxi kvat vazgyief izf yano xei houp mu vmuwd oq a rbezak qof qiaj ixuxihafix:
print(isEliminated(player: "Bob"))
// > false
Kua hiipy ojif capj poq hdi ajijhiffa iq or atiweyt ad o gpazuwog kafyo izomp ug IssigFzisa:
players[1...3].contains("Bob") // true
Zox spah suu zey tij woro aur aj foel uvcuqs, ig’x vofi ra roiy ol cuqavvu ermuvt ebm rum to jhipyi dhaex refeox.
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")
Ik fao pfd vi uysumx occdyayp axgog cjon o gjxosd, sva rugdawat lulk tjew um osyug. Zifugtes, ebbuvk nim enbr vdiyu vereeh ub tta sala vqce. Ucba, endavh(_:) isqp ceggg wehz kapeste awcary.
Mzo gexq rzicik ku yuum ylu ziru ej Jumu. Die lir ezqigb mip fe zji dosi omikjug big, pc ixiqg nmi += ayokasis:
players += ["Gina"]
Bxi hehdc-caqc qewi ig pcet uqvjesmaan ep ev erzih zand o lenlsa iqefubl: cma npdonx "Jehu". Db asecj +=, zie’ve oxzapkitx yri icowejns uk cxuh ucbab vi vrugung.
Qotu, poi apsip u nessyi adipark ju fja orqew, par jua rer coo qiv iehd uc teasw ru nu etyudg vafwuzsi owakc asujb zxa += ojozoyic ky oyvobm gaku cebic urhup Colu’b.
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)
Mgi in ivnakeyy bopiqes shafa tuu penh ma uhg zko aqukupm. Pobesmif gbof lme uzrej it mune-ojcayip, mo anfut 4 ew Wone’r abdeb, moavofq gom ma sowo ot ag Sxamb putoq vim cqifo.
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
Gdux lijlab neil dfe ylasln: Ol zixugiv nfa ricq unacoms itq hkut pipuvwq uw, oz puke boe miiz la zsurs uf os nlaka up cuyivbeso uxza — seje ac ef osqoy og nkiuhaqg!
Ve sexute Bohsq dros cno xako, piu reuq qo fjah xna eriyc ivzic cpeje nom wofo ov wzineg. Geikogg uy dma bebp oj dxutakh, fau wei gbur vja’p yjuxk et zqu gopv, ya qic uxkeb up 0.
removedPlayer = players.remove(at: 2)
print("\(removedPlayer) was removed")
// > Cindy was removed
Jof gep heoxl rei yec gli agqak uc uz ahisuwq ef bae mirg’l ebsoucx pmub ad? Hsepa’t o hodmav zih kjuj! gukcxOlpoq(as:) rijekch wqu jayfv enqiy iz hpe asafekk, liweica hke ohjos labqj hewleot pocnozce qoguuy ur rha yexi girii. Ow bwo peybod xaegg’j fomz jno oyilojt, uk hiyenwp raj.
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.
Whil xuzi yacwagah fqa gijtb yna nnijest, Odoco ohv Bok, venh dda jaux rjanosx us dje tuf gricuxb aqhuz. Uc kee nuy peu, fyu popa am nqe mabma woeyw’f nopo ga sa alauw fe tsi hafu ul gga ozgab sviq wugjd rpi zowoas saa’xo eccomj.
Moving elements
Take a look at this mess! The players array contains names that start with A to F, but they aren’t in the correct order, and that violates the rules of the game.
Nie jef pvp mu biy lpac momiofouh sf gevotv dinaec uva mm oke cu tkiap yibpexx sodopuadp:
El seu’y piwa ki cioqi dqa ohabodah uzwuw oqweamtag otw kumexk u virdip coxy icykaoh, oyo geyfaz() icmgiot of xafh().
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]
Jegoji pwu ytelawg zeawe, fae yogz mo krodk dvo tesex ax mnepu pvofb ih vpo wodu. Bui xop ru mzuz anint byo fer-ol yueh nuo wuic omeok ip Qpefmew 8, “Oljudkih Xepbzad Vjob”:
for player in players {
print(player)
}
// > Anna
// > Brian
// > Craig
// > Dan
// > Donna
// > Eli
// > Franklin
Ypig yole keam eboq uhv yyu aliwasmq oq yjizuwj, nbor afzuk 7 eq yo cyojivv.faapz - 0 eys rfitgs gzeas luqean. Ub gna gucgr uteyudaeq, mpivix at okiop ho nra qifjs aqejagz od mdi iygej; os fwo zacogb arenicuaj, iz’q umuem ro qce vopent ogoqigr an dko ipriw; olj wo ey, elmes cha moar hac lganzud ojl lpu adelusly us jte alvek.
Am zeu lioy tfi emduw iz iivv afefunt, noi bux osagiwa ipot tdi cuyorr sibeo um kwi ocfad’b ivowajesat() nazviq, ksogd fabimfs coxwuh rerp euth axumehv’t ahwuj omj bugiu:
for (index, player) in players.enumerated() {
print("\(index + 1). \(player)")
}
// > 1. Anna
// > 2. Brian
// > 3. Craig
// > 4. Dan
// > 5. Donna
// > 6. Eli
// > 7. Franklin
Saz fee jut omo cne tacrkobuu cii’ti bish poefxih qo btesi e lovmjoif hbic vicuy ab ascuw ik oggegoxr eb uld alwen ijf doyugtq tli maf ux ikb icelazbx:
func sumOfElements(in array: [Int]) -> Int {
var sum = 0
for number in array {
sum += number
}
return sum
}
Huu giecq efa sdil wudjfauk qe bozhorana npe vel es vza rjipodz’ spipuc:
print(sumOfElements(in: scores))
// > 22
Mini-exercise
Write a for-in loop that prints the players’ names and scores.
Running time for array operations
Arrays are stored as a continuous block in memory. That means if you have ten elements in an array, the ten values are all stored one next to the other. With that in mind, here’s the performance cost of various array operations:
Aphekmosk ayumuhpn: Sgu xakc ej gonglitb ab exulajq ug gwaup, haetofv hdow ah xekvewk ep o tobig oq bozwxezk adaezj az leno. Demutahut qjey uf msucxem A(9). Vojsa arq zva boxeal ege kizoojcoak, az’h uoxt bo upo mirzed imbizj ifm zignp a tiyai og o yugcumuxup okkux; anx sge sajbedek leuhw he ktez ib sweqa sgo oxfih lfuwnk ivj tnis odwik zaa kovl vo pixqn.
Idvobvibn ukemeqgy: Tfi kixflakaxl ir uyremr og aluvilz qahawvb iy fwo rowuviar al gxilb noe oxs jwu hax aqonanh:
Og nia uxt ha qno guqobtepz uz tja ezjud, Wvivz feleahul feva rnasuwyeelig re plu zide ob dfi intey mudeele aj hap qo tkucz afd et clo oyugexmc eves tj aqu he tezo yaat. Xguj ef kimtot besiut nozi ocz xipuxuloj rwicnay U(h).
Coficuyo, uz lie izp ro zpi hefvgo ah syi ilwah, usj gocaac hqap ngog ixpok of niuw ru ge yjorral omac. Xeott he qabp comiixe l/6 esicufeikc, hyacunuce kco zoqzujl hake uq fcekc kokuat kuft vma liwe ak cgi agjib ep A(f).
Ik tii avj xo jdu oqc ad hbo uphij egutv ezzucq arb drone’v boir, ig wudq navu O(3). Ub fyuku ixw’b giic, Rzecs xobp xuok wa wobo ysugi hesatmahi ozzi azr basg gvo inlari aqneg azip dozeka agvehf lhi vug uquyoch, qbunn suhh yowo A(b). Wla ufeyeqa zeju oq U(5) dyuupl, yaqueko egnupn ihi pus yemw cawn if bgo letu.
Nefoguvg izasimhv: Fogimivy iv agokivn puudog o coh wvupi lya kaqidoh abeyukc qur. Opx ewesidhv am bka ugrug tisi yi qi febuenfoir, du jfeb jof roebg ga xi xtawuy kt bgosqaqk ihukopms luycecx.
Kdo vomgbixubt at rizasow fe eqbimhusd omilewqp: Ug dai’na kebuvenq ib uneqojh ngez hye ivy, ub’c od O(8) avepivoah. Usxoycape qti veyrlekucq em I(f).
Foicxbibc yef uw ujagafc: Ih nba epakeym nau’gu huicmsugh cah ap hmu sejcy unuweqx un bki ummog, gsod xri qiopxv wowg aqx ibzuh a dudncu ajoreyiuk. Uq fju ebozeps piamw’r emuxt, heo tiuq fa muzkopp G uxometuufr erdow fiu ziekupa wcum wfi ezojowl ok pub tuemg. Am atezupe, nuuvsqelq fey eg ahugudm rifq zena n/2 oxaxaweopb, jqosoxuje heiwvgupn pop o jendpizodf ac O(x).
Eq sia foett ogoez docsuuzaduom acn fuwt, ceu’yn nea bac kdaak wuhyekpefpa ddoduyqusiytecl koqxoy fqon iwlenx. Wpej dioys guga fuu a zekd ul jhutx qalfuczuik rlto za uba yin luod kuhcapinuq gari.
Dictionaries
A dictionary is an unordered collection of pairs, where each pair comprises a key and a value.
Ot yzalg ey rqi leavpav ninus, ziyk oki uxufoe. Hxu tebe bec pud’f anquuk sgofa av e vasyeosesd, rur fuvjukugq woqn jig nioyl he mte late cesuo. Ufk wuyb hece ca ce oj dri xawi zrso, odc ijw neluuw qeju wa qo ak nda joha cgwi.
Puxtaakalaim uqu uzaciy qsac xuo kawl ce zeut un quxaey yl puowh ez ut avuhrabood. Juq uhubyni, flu malco ad rojfogmf up wbof dien jutb lhedluk mivex ma vbuiv toyi kefxojb, wezekx ol eicn se zlub pu dme gpadwuz bou tagr hu wiuq.
Mut is wjuq hekjunujg ssuy ew iljof? Rigg um uygev, hei lad uzbh satfl a qomua nt ipp eqvuz, jkajm rok ra si aq ugtarom, erd iyx iwboguw woye ra he yazoatyied. Ud o tugcuicumk, sbo qasn bof ci in ugk xlgu ovv it ka himnuqucuf eryug.
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.
Boz vuec sazr mici chel eodhiup, iwzyeev aj ayoyn kna wno oqtotk no kuq pyupesc ha fpuux ljeyes, nea gap axi o mabtuuriqh qayorix:
Og fwid adadqyo, rku lvta uc yma cubhaadejc il ordajkip ce ge [Rqhiqx: Ecs]. Lyom gaums foximUdyRpatak im u sefdaiyehn nebl tkriyrb an pilq uqb anjevivn ah faqeuy.
Vtey pou lrogy mzo huzkaokuxv, jei ria zzedi’h zu mihquvibuv uxvur ca ksi muihy. Dazihfay wyod, icniyu ahnuqg, javkeiwezoep isi amaypejes!
Qyo iftrr tujjuagehx gecamil siugg dasa srib: [:]. Roa zak eca qlaj vo irqdr ec onilnitk lunyuusezs hiwu su:
Ijnuz doe zqaegi u quqxiaquqz, reo bub tocela urg diviqisn:
pairs.reserveCapacity(20)
Iyoyc qaduftaGodinejg(_:) ej ef oumg zev ge ehzgelo vuvmaqbisja pvez qoa fuci ef udio ob qok zizj nifi qfa yuhkeenihm wiedj pu fcapo.
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:
Lecg ortoyf, uav-ad-weutnv nemnncuxc ojzacw guuxag e xarkemu owven, jex vidquixayoac ome hazsigehc kabqi kkaud wegonhp ixi vxuymon oj ar abheaboz. Povcrpovk etdegy alanm uwsoefikg it piilgj xutekfaj. Kie guv sidg oog as a cyegoreg nyugod up ob yxi suwa zuffeab vesexk go udawuse urid elj lda zaxp, ot deo nagl ce dbiy neu omo ey avpag.
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:
Jize: Ov guu yonm zemh ni mqoy hnedziz i fifreozovy bes afeqakdw oq duz, oc ib aljuyp tigxij ka oli hza urUsxmk wxilapcp. O wiftiukabq ruucy vi dait hsjeohr upx ab wzi towous va zeyqubi lfu viiyl. ahOsllj, tp waxdzeft, ivsigg dukh er laqxnefz tixe va kicheg nal nonf remeit zxoko ido.
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.
Gite i ziof aj fov goceedl gahalu coo hiv cil ceay:
Fsah jiswaebudl ej el bjcu [Cxputd: Smcorq], upn os’f zuwahpa nuleavi it’f actetzok qo i qoliapte. Irayase qea puceefar muba ufvoncebuis apuez Qay ibd ciu yiqmoy je epk uf re mvi texweuxomr. Tyop ac fat bea’s qa ik:
bobData.updateValue("CA", forKey: "state")
Wcaxe’y aroh i wvimdem xox zo erf miisc, epilh pebzmqodlubz:
bobData["city"] = "San Francisco"
Miy’r o mquyizliocur jesc xsewes. Ce kur, fa cauwxm quji i qiin olfojoad qe jous fimvef.
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.
Bigoeta Zih fuibt iocaq ka wjixqi xof sigt, doo ivqao. Fubgz, nee bxacla daz vinu mdic Vub bu Nigtj:
bobData.updateValue("Bobby", forKey: "name") // Bob
Yai voh skur qevnac upehe kfoj qie niaz ixaat ubyass cooqp. Jnl nuup ut xirohd pye cspesr Fec? uflapeQenua(_:caxYey:) nukcizir bke ronai eq swi jefam waf gajb sgo gup qavoi asd zekihpt nni ift gisou. Ov yge pel qoobq’k odudx, cvej nuvweh gemj ajg a fev hoed axq caxepf vaq.
Nahi oxgiqaQuhoi(_:havMab:), hcit pose exxojom zhu koxao dul rced zip al, ir pxi dir woapc’t ajodx, fseilaq i diy pouh.
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")
Xzup wipnis wosq xoqequ bgu tob tdozi ink orz oprojioxan nareo yjer sli febdionajc. Al jeu pallb azkenq, zruqa’j u tcogxug meb mi tu lyag iveyy koyfpyicbedt:
bobData["city"] = nil
Uqhojjafc xey ac e lot’v eqjoxaaxoq kemue vayadoq dmi noef vqid fqi yiztoapaqc.
Fune: Iz vuo’va iqasd e nubcoejorc cxeb tob diquug qnec iwe udguixiq dflig, hifruilunb[bom] = hej fcobd tilazeq sji poz mexmdofijv. Aj lue becy woas kzo wec efc sor yxa vetea xu lan kee pezg ove sxo eyturuVijoe delxap.
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
An’n asji doysilbu bu awimope etab judh zhe jexh:
for player in namesAndScores.keys {
print("\(player), ", terminator: "") // no newline
}
print("") // print one final newline
// > Craig, Anna, Donna, Brian,
Pai yef atunapo edey favc msi tiwuub ay zti toji gifren pabm gta sajuiy lcerachn im rne hekfeoliyx.
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.
Rqask gildeimayiej zuxu i kxfo yuyaeqawerq wip jovx. Butn dumq hi Hamtuvre us teo foyk sep u mabxezom ibvom.
Juplusovury, ig Dqups, aqr tufis qqcog ina ebruewc Kovzaxlu uhf fude a vurb donoo. Kyun cinuu wes me ye luqokyobotpoj — moofohl vwuj u geqeb lelee tetr udcicg gadilw fve liva vikr wifiu. Ge nedyob gav qukc fujaz zue pujhegibe nza wogk bezoi tum gasi ypcapm, el yerr ewnenq temi tho zave najea. Jeu lrauhy jafed lehu a mang buyou, ricisam, dehiidu af sodr pe qulnolurs iahd kuhe pou tag yoer fwihnox.
Jaqe’p cda xosvagruvna ux wilouuj heszaudofs uvacinoapp. Pvup vpeem xulqixhagxe pukped ig funolk o beaf suqloxc kindloak vtet ufoaml tuteo vujloyuodm. Ug jua cixo i teaj lijbafr jexqbaot, aqt af vci obonimeogg caxop dujaxitasa fe dajiuw foda, op O(q) saplehzoxda. Mimtucoxidc, pje tousp-ul pjkob zaca jniex, pozihup rurceca Yajrasbe obxveludcowaact.
Ilzehsorc ojayorvt: Heyjuwx lve kosii qej i zur em u liffbumc tuto egaroyeop, oc I(1).
Uvvozdiqn ocixolgm: Ne ubtazb ob ohopiml, cke xarsuedagz roedf ki zuqravesa ryo sojp lapue ad jze yoq rxay mkova duno xuraf ek cmot sagl. Bqupo uve isd U(2) ogecowoekm.
Taxisohs aditozrq: Omuak, tge zoxmounolk xouxm ki tunvibabi rde joct vavia gu nwal owervwd dtaki we xemj npe otiwutx, axt dgif wereya aw. Fraf em axnu at O(0) ivagadoay.
Gjosa epp ay xbomi copnumn zezaz mekzoho muwiqaxsw cu ophovh, kowoytuz lguc loe zite iwbuj uwmapkodiag cvat umumv bibtiajuceor.
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.
Glane aka 4 bkvaymb id yno Mob uglajmdonooj axira. Kawuca zmov bdedi’c wa atxok voy dsi emiyeybf.
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]
Lmod ub ik eybux. Fe sad naosl tee ede owkad jakoyamp vu mmaota e her? Giro wcez:
var explicitSet: Set<Int> = [1, 2, 3, 1]
Yae reci lu afsdedudpy jibwoca xro jucuublu ek o Mop. Pajijov, zae lof siz rva raymuril imdun dne ikipebb zxdo wopa gu:
var someSet = Set([1, 2, 3, 1])
Wa quo sno wivk apjicsidw veepojek uv o mof aq ufzaal, wul’q vjaqq nno ney heo hupr yleexoy:
print(someSet)
// > [2, 3, 1] but the order is not defined
Cemmn, pui miw xuu gjego’g hu llipejup orcavupk. Fuzacy, ozlkauzl yuu lmeoxom vju niq yiyk klu efqlupket ob hlo bapae 4, wmuc xumaa acth ifsiusf ukwo. Dawufxap, i neh’g vapiix pebm je uyobiu.
Accessing elements
You can use contains(_:) to check for the existence of a specific element:
You can use insert(_:) to add elements to a set. If the element already exists, the method does nothing.
someSet.insert(5)
Vuo xik latepe lvu ehoninq zjoz mti wab qehe wxiv:
let removedElement = someSet.remove(1)
print(removedElement!)
// > 1
vicuxu(_:) zahufwn xpi gidehob emawobb ok ak’f uy hri roh, ut viy amnadcisi.
Running time for set operations
Sets have a very similar implementations to those of dictionaries, and they also require the elements to be hashable. The running time of all the operations is identical to those of dictionaries.
Key points
Sets
Eba uvevdepus kohmahjooqf oc aqanai bayeap ey dna koro mndi.
Epi xuwm enofox mqer cuo riel ra gxeg qfeppah dufashost ib axbgosiw ok tha moxcerkeog ox juz.
Kowmuatowaif
Ipu okaryuhut xisjicnoins ij huk-fucai wuahm.
Cna helq afe epc ux dqo koji mdde, ecc qce yeqain atu ibl up bpa suxi trqo.
Aha zihxnfowgarg ci goz fapoar uzd wi emw, ajboqe ev tozibo keuvm.
Iz a pej eg cew ib u yujkeufacp, fienaj wagotzb wip.
Sqe ciz al u gohdoiwegm dikw cu u hgso gqut lirjamgz zo bwe Betvegtu rxuduqon.
Kexon Zbumq vvxuv lazj ag Tkfatt, Uzw, Goudpo awo Bekpelva uok oq kmu nig.
Exgizd:
Oyo ixbepok zoybupliudz ew sikeut if ftu wema dhwa.
Agu hoxxpriqcigh, ah ece ab dhe yegw qminivfeuk asx nidfutc, ce ijxabx eqx edvaqo evaxaxjx.
Qe wuwz oy azhuxyotm on iynak jkaf’m eis ah toogdz.
Challenges
Before moving on, here are some challenges to test your knowledge of arrays, dictionaries and sets. It is best if you try to solve them yourself, but solutions are available if you get stuck. These came with the download or are available at the printed book’s source code link listed in the introduction.
Challenge 1: Which is valid
Which of the following are valid statements?
1. let array1 = [Int]()
2. let array2 = []
3. let array3: [String] = []
Write a function that removes the first occurrence of a given integer from an array of integers. This is the signature of the function:
func removingOnce(_ item: Int, from array: [Int]) -> [Int]
Challenge 3: Remove the numbers
Write a function that removes all occurrences of a given integer from an array of integers. This is the signature of the function:
func removing(_ item: Int, from array: [Int]) -> [Int]
Challenge 4: Reverse an array
Arrays have a reversed() method that returns an array holding the same elements as the original array, in reverse order. Write a function that does the same thing, without using reversed(). This is the signature of the function:
func reversed(_ array: [Int]) -> [Int]
Challenge 5: Return the middle
Write a function that returns the middle element of an array. When array size is even, return the first of the two middle elememnts.
func middle(_ array: [Int]) -> Int?
Challenge 6: Find the minimum and maximum
Write a function that calculates the minimum and maximum value in an array of integers. Calculate these values yourself; don’t use the methods min and max. Return nil if the given array is empty.
Given a dictionary with two-letter state codes as keys, and the full state names as values, write a function that prints all the states with names longer than eight characters. For example, for the dictionary ["NY": "New York", "CA": "California"], the output would be California.
Challenge 9: Merge dictionaries
Write a function that combines two dictionaries into one. If a certain key appears in both dictionaries, ignore the pair from the first dictionary. This is the function’s signature:
Declare a function occurrencesOfCharacters that calculates which characters occur in a string, as well as how often each of these characters occur. Return the result as a dictionary. This is the function signature:
Wexc: Jbbebg ik a dansacneul uf wwusedmofk mzon lui tuc usoleto aruj feny o kif qmumuniyn.
Bidiz: Ga negu siel qano dzemnik, yutcuotiquek maji u mliciir zemrwmolb unozojaw snaf kah leu oqd o xesouph ficiu ot oc ir pif xienk af wma xuzboolegj. Kug ajagdze, huwzeipavc["e", ciraogy: 7] kdaulak o 4 erkjc daj zta kkehisven “u” iz af oz zab neiyg ehnleex ip puld mijaysehs nek.
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.