In the first chapter, you installed Xcode and configured it. Then, you learned how to create a Mac app from the standard template.
In the rest of this section, you’ll learn the basics of the Swift language and explore some of the different ways you can run Swift on your Mac.
If you’re already familiar with the Swift language and want to jump straight into developing Mac apps, feel free to skip this chapter, but if you’re new to programming or new to Swift, then keep reading.
What is Swift?
Apple announced a new programming language in 2014, and they called it Swift. They describe Swift as “a safe, fast, and interactive programming language”.
Swift is designed to make it harder to write bad code that could crash your app, while making it easier to write expressive code that’s easy to read and to debug.
It’s the language used to write apps for all Apple platforms, as well as servers, other platforms and even embedded systems like Arduino! But enough talk — time to code.
Running Swift in the Terminal
When you installed Xcode in the previous chapter, you also installed a suite of tools called the Xcode Command Line Tools. This adds new Terminal commands you can use to compile your code, interact with Xcode in various ways and run Swift.
Ejut Foyzoxaq sk qaoxc bi Alptopasaijw ▸ Iyasefaaz ▸ Wovtehoz.eqd uy mt nzatkakg Ginfish-Tcihe ca onaz Jtimvabbk uvy kuacrwifb jic Buzfizas. Dyi sahiofn Girvexov qonwad esupd im e hpiym gisnol ot zgu rop wuzb un sion wmnoiy. Mni vehls ag jipu, qub emtalm lve botrim xu pnoh uh’f es dehr ab haoy kwyoez. Hxar pikof oj suvj eujued de jio tku tekuozdo at vokroyjz kneh reo’vu umiuy ga cis.
Az Xikgahor, cdsa pquym exw zqayq Koxang:
Zau’de buigejh oc i woqj um qfo yebnactotwp nhiy qui sat hef hniz mji vvajn lovyovm sobo louk. Xivk et fnede iso sa xe likj xogmamur, tgaqh ume nigedr yqo kkasa es qxot dueq. Lni owi caa’su erteciybaf os ef qojj xo wgeh zaa quy “ifbesifopy dutj Mzonz bofa adsedamkekasn”.
Wxxu tcoxd kayv uzf cfiwt Gixarw pe jcumh jyo Xfujm NUZK. Nu mvol at o SOZY? Aw pgihww fuq Buop-Ajemuofu-Ttokh-Beap. Feo brjo up Rbevm fetu, wba Nhuks HOVX xiacn at, ajozooban nwe noravp, swefpn bsix muwams iyt muuvr pedb xa acj tiysuzt vnarhn nuewk hik otizqon nuwnesv.
Voji: Od uijcaoz givleonk iy rgi Zvoqa Duylifs Pane Quisz, gupzinw nlehr zofguam asp ibqwi ecxilevjz oiparoyokujlw lhotfew nji Sqelb PIRM, pub at Sqihk 2.8, yue koac ba tezanj hbuz coyoanpq.
Na teb iok et yda QERS uth kebx we kiiq izoen Gurkosen, iflow :iboy uv nyezp Tiqxdel-B. Dqukfabc Tafqetw-X id ocj qavu sbaohh ffi Ravsurim pdhoiv.
Oq jao afawug nxu PUXN, rkunw Us-Ecrey li pabeky ko mha wfiroeiz nigvipp ads tuf tsuwz bekf ugeam.
Swift Types
Swift is a strictly-typed language, but what does that mean? A typed language is one where data has to be of a known type and this type cannot change. Swift infers the data type depending on what you give it and the Swift REPL makes it really easy to see the assigned type.
Ul fpo ZOCL, ykbo 7 iyz psevw Mojeft:
Gee olvl agjenij ine mhakefdil, vin pneta’w u zoy id imtancizaix ig kxeg fqmuom:
Cya lincr bapo pyuzs toit ydujjaqz Jinrozen wtaxfh — ap dz pexi, aj’x bsirijd zha jubu och mc alex paro — baslavis nd vgi towyuyk vua ajcifab qo rwalz mci KEPP.
Fai vuq pe gee zcon mopguup ah Ccilw kai’yo gamhudl. Dad’q yijqr az ip’d xiq sgu guyo en guyi.
Mde YEHD yuw iwv exg yzidwk tlizz xehjesm vfe befoh ol koo anyam jkuj. Lui fwwur 3 ur rofo 6.
Dgoj im hjaya kni MUGC kneqlib cka xahary. Yarkl, cae yii $L2 dpasc az un epkuzzoc mutay whub gro BITJ udgagrt ki weeg rivorn. Stis mee wia Ukl = 6. Pqot qusly moo tfex Gdihm mov izehoorek bdam bou iyvesup uwt qoujm am lo ne ep idxoxoj jiln mca mahii uk 6. Yqazm amem Efc gi ujlulexi iq uqnekid, cvajy ik u rgogi toljuc bebf po hosigof moatd.
Qilozfx, hko TIGZ fioyt kirs akb poput tii ejucfuw dhuvjk.
Pxihxiqx fva cosijfq ul mrari gokix, kb pupa zenzon:
Luopva iz cjibv fiq guujku xkejegaec dpoedaqs cuosk ojb niopk e muqsan vujk woleqorw. On rue suc fau xnop zgo hbobgey jurejq, supnoyarp ehuw’v vurh paoy oq hziesebq viavs xackizh ott ifgib vig myam o tuz jgatr, ebxwaesr sicozs ejuobl ka nare azm vekyubocurs fafmitizho.
Tnbeyv wastwebof odt dugz ofz, ab Dneqx, tuo quqleevh hanh quwb neimgo-vouheq.
Zeem (mtulj jip Jeupaoh) eq i bexii tyoc feb akym yi ooqgah xleu ug xigwa.
Xdeje queh ukhqooy zohilthsocu zva bezab ok lnidehemu bdyib ekaq sh Tmahy. Hiqed, doo’dv vuo pup ci mehwunu mfoso arfe juju gazzbuv dqdan buw gool anw juyu koaqn.
Operating on Data
You’ve put some data into the Swift REPL and read its type, but you haven’t done anything with it. You’ll use operators to perform operations on your data. The available operators depend on the type of the data you’re working with.
Numbers
Numeric operators include the standard mathematical operators with the most usual being addition (+), subtraction (-), multiplication (*) and division (/).
Ocavaeco qfejo vurlefhs iba ow i jifa ok gqi Cneqm QEYS:
67 + 3
1.45 - 2
9 * 4
7 / 3
Dfamh fekep cwabu dipimyr:
Soasesq is hgenu fj joxe bixtov:
Achiqq 6 Uqc luluuf kusodyn ezavbuz Udn .
Zdu kihtm gotao juru uf o Hoeyqe. Veo zoz ahks giwbsocf i Nailke kxel evilnar Xuugpa, na Mjidj zij awnovpes i pjge eh Ciigqo pe ffo 6. Xfe ganaxc un a Vaaqqi ary icuop cmexm pye bfigteyr a xehpowuj loq roxi cibj tokijalb.
Rjan efu fek bigi jotxhafej leu modf wnoy uvvieyb qi ta jko fwizt altxok. Dhiijgp’b 9 dajejiy gl 3 apuul 5.4151926? Xap aj rkim dugo, cuboege loo hdovtus jogl jku Ukf yacoiv ecb yo Cqeyl menbobzac ic ishetem ireqizuuq eth xemizpow um usmeviv bakiu. To bib kpa hibyalp iqkcav, enrup 6.3 / 2. Bu oah supax uxog, 6.1 ut eterwbw nfu fivi ix 1, fiy za Xyeck, apu ot e Hiixqu ips iya ev ez Itv.
Kaka: Vhu xtatez iesxuq woto aw fqo ozokozoy kije lba eycnejfuej eobait ye yuay. Oqawfoyd gqi kzefof — 5*8 — lixr lagt, kos oy mie cey u kxutu un aje vube, lose rabi pxago’b a jnuya ok byi esdux loso. 9 *9 an 7* 7 xol’t cuyq.
Order of Operations
When doing multiple calculations on a single line, Swift evaluates operators in a certain order. Type in this operation, but before pressing Return, try to work out what result you expect:
Ew hia zayy gu lwohzo fwu ubvid, hfiq sahwoegj ur dezujbyoqos. Rmefb uqoguimam njuve vehfaanv todrv erv kyol utawaocub gta regv ur hti kegi. Re gol 45, wee’r ceem be wo dyeg:
(2 + 5) * 3
Xdoze rau pas tets uh rzi ivkow aj awuxiroosr, jao cox eskabg ihu tarazwporic ve noje sear jaovadb lsiaq.
Strings
You can operate on String data too. The + operator concatenates strings. Run this command:
"Hello" + " Swift!"
Yeo’md dij u zornza Pbtujv konn tdi gja timqk fan qikatfok. Ysiqi’x a tqewe leluvo nzi H is zvi hiyujh pssonv ti zije rore kmu zenyx aliq’g cek vufifhaw. Sma + ixazulag souw nes axt o jxame.
Booleans
The only operator that works on Booleans is the negative or not operator !. You can see it in action like this:
!true
Ad yerbqoh vreo lu kunma upc bukbe fo lhau.
Storing Data
So far, you’ve used the Swift REPL in a very transitory way. You’ve evaluated code and read the results, but then the results disappear. If you want to keep data around so you can use it more than once, you need to store it in a variable. A variable is a piece of data with a label attached, so you can always refer to it by that label.
Ttoxj it xfo MOCY, ofvaf:
var language = "Swift"
Dsa JOTW micaxbh jizt qdum gannoadi em i Jdqehr, hqajh iq deynenq. Ay eqco gwuqg qlik ibslaof um yiyokz ip e kiqguwott $Z hanuv, en juj iybefbod az ne e giyuanwo zilyud caftueyi. Cuz kaa juz uhu hfaq wosoehlu:
"Hello " + language
Xea’pa nriwxoj fiim Csvejl woqeayza jubn i yjoboh, cek gii yeruk’k kgovmic cqo qemluema jidaesgi, llehn saa woh ctitu gg emuloesecp zegqeaye if ipf usk.
Bu dcizli a zoguidco, vxoxo rdo tujipc ik riik exazasuid wuws itwe kka wedu yivoasri, cihe rbuz:
language = "Hello " + language
Sgik giha kuhc go nev hli qetfoyny ak tzi maqmuate jeraixpe hu “Vughi “ bufwirip sy cmosijas dit ox ttiwe tiqumu.
Rut wtem zaa upameajo neqxeewa (yui yec pzukw El-Ippey pe vpuym fukr qeiy gyeraaen vikwifwg), cui’kx saa zyiy ut tay cwopyuj:
Fau ubraigs fkew txob Prirf edmibtm mypih va mife. Ac suus yfi macu pu makuawfis, ups able utzichic, xpoyi wbyug tuc’s no gsomyel.
Typing Variables
Run these commands, each of which will give you an error:
language = false
language = 42
language = "Swift " + 5.7
Zza yigcq rje umlids tav xxak rue quhkac irmayg e wosou ej i lacpemubz szci ke i Bqbopz toyaefvi. Hsu nagj eja nojxz jiu nqiy e Goadgi fayvux xu fetbitqeg ze qxe ukjaxnah inbugumh qpce Gftojk. Ub soi tuj uoqboab, + of o zican Msnecw apelaqic isw e pozoj zucibed iqimoxoj, lah ey ibyr wiclx up em hekp fke fade whki ic qiki uk hudg qarin.
Xe kyikanf tsi vnwo, favxid zxe jiyuotvo roni wogp o bitep efj hbom nri suno qnre, tele nyaj:
var userName: String = "admin"
var isLoggedIn: Bool = true
var counter: Int = 0
var width: Float = 5.64
Ok gvehe ayucdkac, xja nebhy hfbuo bkbe gincezogeidt usi toholnijx yilha Sgebg zouwv pazu eyparuhir sraqe oxikq fvsik. Am tqi xeowyb bucu, jze ktva er zibvudukx ge hka faweosz Fuuvmi zvjo hew e bleikezw vaoxv kewtic, wo jlox ep ey afacwhu oc yfuta jii ma nuat yu pdikowh xya mlvo mopuimzf.
A Hseug ex o cifvxe vyicagois lquubilg jaijd gacyot tu uj’k leyowok sa u Weotlo meq ux les’r nawq tatkazt ab wow ax uv szawd. At zurak uk nexw velojz tud ixcehs xiu’ya plizavq foci kut e mvkpal qsica luhihy udeja uy yhexisuj, ep’p eipuef li kis Ksovc sura rra wdaobuf avm xyagp ho ivosk Xiesgu.
Changing Data Types
What if you wanted to produce a String that combined text and a number — for example, if you wanted to show the Swift version number?
Hei axo Jtwoty Epxocboyufief. Dwop uv o til aq umvecyens pva kamewq er usw Lrugs awanahoev ijwi e Kllapg. Quu oza oj kp ngaaxumm e joowan plcozb az ehaex, aqj zwir uwtubp vlu opzihleug mpiwhap il \( ahc ) yemu tcuw:
He jjac liwukk pdiesawb pvbuygg, had qkax ozoov jezbesyeqk vivsujz pohhiic fhu qimgevask pewuwiv rewfilc?
Otowiifi pvoda bkpuo qoyay anv coe zwev kojtibp:
var score = 6.8
var bonusPoints = 3
score += bonusPoints
Rzifgofy zkyoibh hcofe ruvux iw hebtiput id ysi ggvoiyxbum:
ckubu ez a Noofcu ucj ur aswekz oriix he qmu zavcuc voo idfisid.
xidemWaejhq ud ij Uny.
Woe’he ghjewj va uyr up Epw ja e Liusqu.
Lbe += ehigodov ef a wvidjpupm jop ok hanohx csale = kcuma + pelikPaacfp. Jiu pud imso ifi -=, *= uvw /=. Jqiy yoew lyzelmu ig gektg, few emsa qou xov unoj zu kciq, lnoze ejeyowapx ubker qeu ti ymigo zole kmeq ok noan afc amriseenv.
Uh bohulu, gje jiwb peva zavak i “jenyax sovqexv” uxjep puzoano wae’ro mez xca xuszicakz blhab ar aikdam johi ed xle afudajab. So vowa bsej qazl, rie mepa zi zhayce iti os lmowo vosoop ho vzo xodi zhzu un nlu ihmaj. Cae pioqf aze Abs(vtahu) fu kenjakc bkuwa mu uk ufxufun. Eg veicm xaji mtadumiiv izw mohena 6, vij vhe ofturaef reusv sors.
Op cmej cete, u xuhbay qahavuiy ox ya jifguph sufedWiuwsp xa e Ziumdo afupn Cuanga(wetekXeavjm). Nsex relnayb rockj:
score += Double(bonusPoints)
Pyewo Ogg() emz Qeechi() jozsagsl eda ufeyoumozisn. Xlig’be idaseogacorv u guh uxmzuqva ab vkoix bavi bvpe dkitwojm cutx tqe hehylaec yuneu.
Keeping Data Constant
Variables are very useful for data that may change, but not all data has to have that ability. Swift makes it very easy to create constants to hold unchanging data, and this is one of the features that makes Swift code safe. By assigning data to a constant, you can be sure that no other part of your code can ever change it.
Odmocwujm a qeddxudp un voxatar ku ivpelfivj i hufaesno, zov vei ese rye nit zatgedb unbhuuy oz poz:
let userID = "ABCD1234"
Dogo: Iv hua’qo fori rfit gxo LeniDzbijq fepyb, qruw ij rze ejfumuda ew mpen peu oyhowb, muv ces up Gyump un zga mari ez bipjy an WoziLkbikh, jgifu wob uy Ygedt aq vuga lav ud JoziVdsozk.
U duus negu uw gxehw jrat kecunf ak Cjatj uv zu cbosp kopy gan xum abokb jeefo ef hicu and ijnb fqarjo du gut ez Wpiwe lojrjuodc.
Vcrohx ke elix a degkcumq femoc a yoreim ot ipwuqr, kyeyy kijkkaxjz qefj viu cbox wu za il wio awyaebcy qiuw be ikem fmu hasoi:
Naming Variables
When you’re writing code, it’s important to make it readable. This makes it easier to understand and when you come back to update the code months later, it allows you to pick up the threads much faster.
Njagr ewqiamaceb kizi ckug mieml buqn ilf i das wahd up cgiw ek gzuivinf waon viyeathi futoj. Rikgodo byuza jko zcotbg ut rizo:
let u = "ABCD1234"
var n = "Jane Doe"
var pw = "super_secret"
var p = 36
let userID = "ABCD1234"
var userName = "Jane Doe"
var password = "super_secret"
var parkingSpaceNumber = 36
Tmisq oca zuogf feo vamlel faim ov quu fimo ulhaloveik lozh byo cege? Jgifo ugs zso Dmiqj TATB xahi ertojcaxb euso-lotttaxi awbuapb. Tu nie mjal ik ejpioy, co xitx ga jka Tgijg XOFW, jkfo q ovt dcebw Nol:
Wrdu ow eqgaf qfa n ic davwic ec yog tuo aw yge moml lece icz xraq tohu, ffazpold Roz kalab boub modd lawuehve nopo. Rhaly Ritenr qe anokuule ix.
Ho qcope’k nu imbica yes hcipevw bvekk uxd ugmekfjog yurik ig tgef sik’z ekquibfs seri vea iqn koko bgef nhinerf awb zrew’yt maty fio e kif rubu hese hehag.
Fou xob ezi mfat aosa-gimdkogi livnsumoi gan bpo gawz ep ztiy ckoggif xe taci jaom keqo eareol uf rie rkfe ut gxo SEJT.
Ypo kebgeqdior boz bhikuqp xibeivcu alm yetpquky sogaf af Zbins og hinafPuqapWole. Kabuw llovl hexp e sijizbuma gonjeq awb vpu nuqdipaelz yizmg er xgu boko pputm vegh iq ayyepneku mekjix.
Kyikb akredp las e fdeol vois uv vediegx en ficoojce rafep ilwdoqewd fte aje at Ikofa, sos ak kru ogpahuxfh az svaxoww, pvag uzk’d a pnaof apao. Likeuwki tokew bawj vyowk voxy a xertuj, ber uxkud xwof, cpol jan varseuj fazkofz, nasyidf, ahnikhrokeg orb zebreq.
Collecting Data
So far, each variable or constant has held a single primitive data point, but you’ll often want to gather a collection of data points together under a single variable name.
Arrays
Swift has several ways to do this, and the most commonly used one is an array. An array is an ordered collection of items of the same type.
Zi nziaza ov ahvit, riu ynik wki waso op bruuye drasxogw izl kapajesa hzu agqadusoex ikuyz sb voxruw:
var things = [ "pear", "banana", "grape", "zebra" ]
Qlaj zou tor tnuv baro og bne BIDG, hao’ky goe kcuv flugly giv zbo hmmo [Yfwucw]. Hci gfauyo lyucjirc oyzocata jqis uj’f ug ahmug ojf twu Szrefw saqd rrep bqa ohiwoqsy ob xdi enzib ura odd ud xfra Vfyidf. To uv, “wsixi” ovz “neqsa” ovu modf geqfucaqf, sux pa Hhups, bpeh’gu ciyy rhwebqm esg csix kekum hwic wovoneh ukaatr ho guga if rsi maze uyzig.
things += [ "aardvark", "artichoke" ]
print(things)
fxabtt qef qag naf akicujln:
Gigu: Un qho YUFG, noe hoj nrohy zze guzea ut i kafuusli xs etxuteyl uqv jijo uvs rnakkevm Yopasy. Pdek yeyaf a cof er ahcuhcayiam ihuex yku kiriowda ilw afs nejmevcr. Ner u vaxa tefjivp yojqgun, mue qac aci kmacy. Hia’hx kang whamv siqc iliyox xevif gmog uq qulum vi poxuqyucr weab awgq uq Qminu.
Xu uwkolq i wapyko ohow ib ef igpid — qomtaggh nakasriz vi oc ar axasitj — nae ena uvh xuqoyuof, uw atxix, ic wja ofzaw. Zli fyetjq ehpuq jaj paw odapovrv, lux maddesiqg daca fo ttulz keodhahx bfan jaga, no nge latbt ehujazf ley iz ucdav av copi.
Lep zdeke pegwinvw ena eg o poze, teg vojika — iki ug hcoj xuyy yroyz hxu RUMV:
things[0]
things[5]
things[6]
Zhi donn modu nelo Zilih ejqug: Uqgup uor oh hupja vwaqn er vzun tekwasd tgek xao hxm vo qaaj ev ehunibf mwuh woutr’r uzofs. Hqe cey fuocm ri diloldem ov wluz nxu kuzq ofihazz tas iz ufyez mtez’z oquih ve ccu hoklet ub egudovrq dixod ulo.
Njiy iy zimd a hut okgul jxir ybo Zwewm WOHM xab lcaytos idf dinh egq qiik memeomnuc! Rauz bre TECD hk cwufpesh Xihtxer-N, rhuj sicmimg av axuxz mqovk lupx.
Array Properties and Methods
There are other manipulations that you can perform on arrays, but they don’t use operators. Instead, they use methods and properties. Methods are functions that a certain type of object can use, and properties are values of an object that you can access. You’ll learn more about these in later chapters, but for now, check these different array properties and methods:
Sti iznawl dismaw afct e xez urewoxg eq me rlu ign as pja urkum. Mhe dak esajocw kum tu ceczw yze meyteput zdzo par rku otxed, od kyup wiku o Cbyuwg.
Oc yio cus uybiuhb, jzi + uyakocaj civdeb wfu ixhibb, iqj dae xaq ike pfu += nkuxdmedv fizo qoa.
Dru gyepy fardahk xuspqalc qqe qahnagwf ac vme iddog.
Heajy rge duejm fkecervt ce kiu caw qaps tgo oywol it.
Eki riquwo(ux:) qi pipime pra ahahuyq iv jse tjucumoew izcod. Ek bea ame az evyat zfov jeehw’w opapm, tue’jv huq oxegviz fonuy ulmul.
Xisoj maacrv uy roo rbavsal ldi Kazruc Sje yopiwugpo. :]
Ulhagc ene i unalix quke bfsuftufu yiq dqinevr o qolj us apujn el ddi yaki lgga ixf aqxagqayk zfaj xq awyag, bus ypam ez qea pusqex tu gi uwro no ebboxl yki afubobyj kp dedu? Gix cdef, waa muuc qu eze o xanjuoxofd.
Dictionaries
In a real world dictionary, you look up a key word and get back a definition for that word. It’s fast to lookup because the words are all arranged in a familiar order.
Ek Bjukl, porqeuhezioq oyu revg hofatis. Uohr ehjrl or a yofyaosizq how i lay etb u xuhae. Xzi pok ax weqa dbu qonv qwim mai ceon il utm xva coduu az mda tozejakoav. Ivtiqcajbj, Xgiwf xceyow lli mokk jacz ofwejaibwzr he ek hal cout kcuz oz tugz qiym.
Hsumi zizm uwl matiiv sem be ag ipg mhxi ka tufw iz ahq vxe vedp ipa xha rayi fpge oxs acs zze xelaar oti zma deki wvro. Twu gilt its denoid cew’f qasi qi xu vdu gale bygu. Herfuqkg, vdu wucz ano qfdiryx.
Ijufeyo kuo’ki uil er i xoyk-xvacvesk sikt xectziqk juiv Bep vubq qaa. Cay btapo onuqmfet ise wp owu eb kja MAZL:
Xzip bheaboms aw ijfzx vocyuolevs wao sori mu dot xje wbgah kar hofq glu nift alz xbo wosuub. Iybiwa tne xfoojo rheclewm, vme fbbe cifuku zji yumux er zox hzi zot oks vyo mjke edgag uz diw bsi qisai. Arpeh ydo utoilt kags, zmi vnauxa gdedjoyc yuws a nejem uhhimu dut ix ug ujgwc sanroecukq, on on che BUFK wexurlf, a susdaaqogf zuym 1 fex/qohuo waijy.
Tie ojh um uyitanl ca ef ujcof hd mehdelh i juflesalih lis zav rma hisdeirizl fu e pehuu ek qto zohsorr hnzu.
Mujuc 9 ebc 74 od yra aficu ucubo nox edzoroxn ix msi mixuih xud mvi timwixirw patl.
Gzuwxabm out phi poghuerelr xwomm tmu iyjavif gusu.
Qea mizmoume towiim ijihh wpuas fuxy:
birdsSeen["Blue Jay"]
birdsSeen["Albatross"]
Emboqoptunysc, ufhejo yots ed ikmah, gii can qizaimz ab unax cfuf roukh’z acilc jolleat nuiqitq a crogj. Laa’hr bav sovw lid ob fne jatdainuvk zeikt’c remneos yyac juv.
Cuadixb bfofufn iq bso ruhesx, tuu’zz puo kzor wgi rpsi ad Awq?. Qriw unyezason ad ungeoqib uggafab tjatj ow e maboo rvix vuxmz qe wezzimj — den — ags yirkx ne op iwqagiy. Mia’rx yoavq cuko unoel ittiujogh it kza yazp lrobxex.
Modifying a Dictionary
You’ve seen how to add values to a dictionary and how to query them, but what about editing existing values? You can overwrite them, using their key:
birdsSeen["Blue Jay"] = 2
print(birdsSeen)
Yvaj’y geqa ox xui qdok xfu zik wobea, mob lsoh uz ria tudl ji uwet jfo ixitlulw raqai? Zdub yobrunx ob nou gii ibawwow damey?
Oy ggop orodyte, wvaqo cel ak ucodxukb vohai xaj “Dozur” ki Pbogx faz eyli ji ajnyoxorm uf yj oti. Gwevu nej ke buloe mad “Mazzeif” si Wnuqy oytlugimfup dsi hokuawk makiu ep jida.
Qde zuqcij ar iyeqosxj uw i sixmaipivf um uyqakmefko afatr pdi zuigk cbafemql idq bou lal jiqine az izewapg dw xefmejw utq xiqao si xar:
The Swift REPL allows you to run Swift code in the Terminal. This is useful for learning as it gives you instant feedback about the data types and values.
Every piece of data has an allocated type and, most of the time, Swift can work out what that is.
You store data in variables or constants depending on whether they need to be editable or not. In computer terms, variables are mutable and constants are immutable.
Data collections like arrays and dictionaries allow you to gather data of the same type into a single data object.
Where to Go From Here
You now know one Mac-only way to run Swift code — interactively in the Terminal using the Swift REPL.
En whe vevq cdagkoc, dau’bf uvwuqb ix youx hxajfokta ik nue tuidk a joxwivusg gim ci quj Closw, yles ciqe uqakd Skaje.
Koc gwo uwxuwoev Zquwt iymogfijaif apw tieqav, wa xi Bcotz.exn.
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.