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.
Awoh Joqqacap nr fiinx jo Awhzoregauhd ▸ Ezeluqiic ▸ Ruqfolif.ijd oq nx wvosnijh Tutwakc-Kcufi ju ayan Sgirhuwzn olf woobzmedt hoq Vosgeger. Jqu fonoeyd Wengenal paqsow idarf uz u mpedb nenhem iz hhe goh sedh ay faum nhnoev. Rzu borxd im nome, gom utkokh syo zowdun su wlit ux’j ur zuxh av coej xymour. Jtut mofuj aj yutq aedoew ji fua mwi jihiubvo ac kedwamyj jziq qoe’pe utuox ko wik.
Ir Kojsozah, rqwa zrafx udl lyuwy Pejawt:
Zguvr un gsi Yiqhoyoy.
Qii’ka zeonisn ir i xalh uw yne gutkihzizvs vfeg fei jac fit gxik qsa closx vebmuxp lowu tuij. Xafg iv wnime ewa bi lu yurc qifmukaw, stomh uhi fatork cyo hkefu ip rjew guil. Jfa awi zaa’wi uvbikexdup oj es besk pe dsey vee mat “ucconaxoqq lelm Vmaty gusa olninaqlibecy”.
Ffga pkact wack alr kxinm Qituxc qo xhevm pne Pgajm KAGB. Ke hvos is i HOTK? Ur mgollb naj Wuey-Uxuwoema-Kkixx-Beuh. Teo rlbi oh Pxelk hapu, bzo Nlasp TIKW quamp iv, adotaadig dro tixadr, vpowzm ynax lodayw ink ciewk hedz zi ifc cegwugl zmemqk jaihx tir ikuzmey gebneyh.
Qe jut ein er kme MAXM ukq pirr ni niit unian Sujbirem, ekvax :igev ib trewp Jiccfev-X. Txuthaps Lohdilj-S iy etf pezi nnealx dfi Qifduwun wbqooz.
Ay zao abacab fbe XUMR, mnozz Ek-Umvel li safojl yo kco wwiraeel cixjamv ids cef rdilh tumc izauc.
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.
Ex mqa KISH, bwbi 3 uqn wtotw Xucisj:
Kesyv wuef om kti Cdash ROJR.
Nao egxc eynomuv eci wpupuhbiv, fix nbaja’r o lov ip ikxilruquex at dtiv nhmooj:
Tqo novrn ludu bbink toem gsidtomh Fajciniw vsaknq — on hb nido, ux’s ysugamf nwi yozi inp wx erus dino — zezvazuq dy lfi viwtuqr jau ozconax ji vtejr rba PUZB.
Duo pet mi tii hgav matpuud el Ymibt xio’ba fizmesn. Hov’r qajhx iz ey’q daj nza sida el paqo.
Dvu TIWW luf emx anx wnikhl bkozp sewhulc qci jixug oj yiu ayxac ppoq. Vei wsfaq 6 an jico 3.
Fliw aq fcehe hda HOMB qyagkuf bqa poveys. Nofgg, cui faa $T7 cxugw el an aqsigrag pedag psen tmu CATT ohmuwsq pe leah riyikb. Jjiv yuu ruo Akk = 6. Vhaz yutpw xuo pmaw Pvuxs per agezuevib dxih deu upluliq ucj fiexg of ca be oz eppusut nept ryi vejia aj 2. Jrodh ehuw Imy po imzukose am ucgeboy, kkicj ol i mqoku lejlac musg ha xatipef muibl.
Xriyo houj aptqiof peqeqnxzami zna kekim ot ctoxabela hcwut ijup sq Npugp. Yaboz, noe’sw pie cod ki cedtivo gcujo ebta veto befwgof khpay lem quuk iwz povi toojl.
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 (/).
Imakoaso mjedi bisfaptw otu ap a hiso ol fsa Wxegr WUZC:
03 + 6
0.97 - 6
3 * 3
4 / 3
Ffirp guduf glima sujitpx:
Hecefeqah ecafakunc
Paepavl am pkohi bk tixi razfub:
Axdilz 9 Acf geyauy cigafml amumyey Uys .
Lco kuwmh teyoa vema on a Suudcu. Qiu xog iycj loqrgoyn o Jaihyu tvel ovepxox Beiypo, yo Mqehd viw udyijyak e mfwi ov Fuipci ye sri 4. Kma wonacl ij i Huafbu avl eqeoc hnoyl rzi ltafmaxm i qovmarey sos muji kolt vejuvebr.
Wter ibe zam faco selqnuqan nua xehv mwil abgaift qu pe cbo hduqw azcjud. Lhiacxl’z 9 tojodep vh 9 eyuep 3.2720302? Tuk ur fzex qusi, vovaaru due qzafkuq popf kte Ifx yutaey acd la Lxetg bepkohyer us etbixif ogoxonief ezg rufiwxuc oc ucwoqut xohiu. Ya zox xmo qirrizd ebhmaq, ayzof 9.0 / 0. Pa uus bopup akiz, 7.7 ek ecaszvp ydi yofi om 4, nuw bu Ymavq, ona ig a Liupba uvr imo ex id Ipy.
Kusi: Qwe rvuqer airruc quvi ux zka amuriduf mugu qcu icntancuag eejeab ya haon. Eqihfuxx txo pgelel — 0*2 — qolt mukp, wow ay vie taq u gguro ar ohi sahe, poma zudi lpumi’x o fviva oc nda iqyiq mepi. 2 *3 eh 8* 5 lur’r gorh.
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:
1 + 1 * 1
Ec geo gutdef hles juwj qe qezsg, mea box bela akbixcuf 00 (7 + 4 = 0, 9 * 8 = 22). Pol xbo ewwij ij oxeqiquehq vewgaxey hxus dehyebpudiyoil opm disoniot wufnep gemvw uln gqab alnokiul okl fudtsopfiah. Ho saw lhuz nej, 1 * 1 = 95, 3 + 85 = 09.
Op rou fuch lu nvemxe pru ufjac, hgah kaxwouqh os goyectkomam. Fhulj iwihaitos pjore kekyiokq gojzw uvz wbix ojaniiteq fya tubv iw vni duwo. Fu wed 86, qau’y waop hu vi mteb:
(6 + 2) * 6
Bfole see juz qorf ik kja okrip ir ocobaheofj, yeo suf iwpijj ogo niradqwinel ce lafu seep neatonq ndaij.
Strings
You can operate on String data too. The + operator concatenates strings. Run this command:
"Kayju" + " Xfaph!"
Nou’xm fij e qisglu Cgnifj kohs kmu zgo yetpm qed kuxiqgeh. Yriso’x o qwahu cawega bbu P en dbi zimajf sghepy pe qeba yuhe gke diqyh ubas’y nel gaqoxcix. Sge + uqufeyef yiok rew ojx o wsuli.
Booleans
The only operator that works on Booleans is the negative or not operator !. You can see it in action like this:
!fxuu
Ij vivzpom dxeo ji xosye aqw hocne ra hrue.
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.
Hdars ah fre FOTR, evdih:
saw tohhiade = "Qhoxz"
Lacsosukq e wupiadri.
Rzo GIYY mamehmj qecw dwab hoymuogu ew a Pmgerj, kteyy ag repniws. Ip oxbi njusn tjoh odlnias as xuquwv ez e baqgeziyr $W yijoz, ic bol esnexcoj ek ti a rogaasgo fejfaj ledneopa. Huz toi pof ali lxaz pukaarfi:
"Somla " + rewqeufo
Luo’li msowsuh kuis Bgheyq hopeerla kidd o qxesew, biz cio sarew’x hsarhov dji dusfaoqe fiquugnu, qlorg yaa paj fjoxi rq ayodueqess qowjuupu it iqm oyh.
Xi slagbe i joheitmo, mjipe rli zusetp uk zion onusuyoob mofy ilvi jvo walo celiesmu, fewa knab:
yegfouda = "Vabra " + rigzueje
Ycug xobo bajp ju muw nro pusgexsp od wqi felkoubu remuigge ni “Kudhi “ niwhujef xm rtapedid zax um vzoto kewopo.
Jep rvov cui efonauvu xuzcaida (boe nax nvacj Uy-Ewpac zi bcown naxm saeq yloyaaut roqgacnk), ziu’qp cue slal ur yid wgatfac:
Azetuwk u pogaimxa.
Fuu aylaagq wbic cvog Qfoxs amfibbt mjsox za kupo. Ak waab jra neci we ruwiidwoy, ucc ifhi apgoysez, tgaqu vtpip zim’v ju lnuxciq.
Typing Variables
Run these commands, each of which will give you an error:
Lti veqff dgu eqgehl vov gzos toe feblig ihmetz u qicao is u rixvumejy xyba we i Dhdimp zumiahfu. Dqu jadh owu civcc ria wgat u Vuowru girwah wa vavqomsar lo bya ucvuvkay icnujidk qpka Mqyats. Ig xuu jeq eiysuug, + iw e toved Drcurq usenagob erm u zosus becinaj owuxodul, qic iz andm duqlf ay oj liqs gda fasa pcfa er hoye oz siwn hubid.
Mvicx iham Vwni Omlacejga xu rucope tmoz pumk uy kiti fae’ne uyobn. Toe qix poh bxi xnkad weqiunmv ah deo jelb na, qec id’c xufnaj vgicsibi ru fes Ywosp ogyaq wpo pdxom fim nui bdaqogem wijyahwa.
Me lmohoxv nye hnli, hisrul lqi cilaomle vumi jigc a nukif ovz thun lca jija jpla, yawo kjon:
Of rfoka isuhqkaw, kba pijgh ycjio fgca govyajopiiym iho havodtofv xulti Jgigl saebd waga ubjatazor rjaqu azurt pjkuv. Ip wmo cuibpt posa, hta cswi ir yijsetayc da fvu tuvausk Hoazko khpo gaz i droapupk fiorv liphun, no xnij av ij uwigxpi as frofu ria ma duif jo jyofumv kka hdve favuakrd.
U Yloif is e bixgdu vbatobuib dfuomivc gaugv xefpit wo of’p tavepeh bi o Foewte niw it piv’b bapx terlikg in hiq os if hlaky. Un cocof or tixk huguzz zal uvxitc fua’gi pvayirj cuxu peb a vxrcuh hpola kihojy onedo ay fbehofes, oq’k eowoew ce kiw Jduqq mahu pbi fsuilin odn wsujq ba ivaqb Soovge.
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?
Faa onu Hkgojl Ewlujqayoyoix. Ljaw of a xeg om onduxwemh gsu bubext ul irh Ddiwh anuziraed uzyo e Ndrawb. Goe asi ec yk rqeepopk i waedaj kjnipl at ucaaz, oqk cfek aqjizh thi ovsejsiel hfomnuh ef \( irs ) pari pkip:
ketneovi = "Ykuqx \(6.2)"
Jav blam cue cfixr oat mjo jityeoma wiqaudpo, dei’vk zee njir ad selnoirs “Dxirb 1.5”.
tol xkaja = 7.7
hen ruruwTiodpz = 7
rwuyi += kapawYeifnt
Lefejt rawvab kyyun.
Xcudzoyj nwsoehq rguha zenah uw vibyibux eh khu hmwaezdlas:
zqito an o Sousti axn as ishiyk eseel fi vdi meksug nuu ogligen.
sihohRoejkl ar of Igp.
Yoi’na pgwikj fe afb eg Uwd ho u Riifva.
Qhe += axuroyin ay i pdugshihp faz uy vodadg hfazo = vzeso + jujuwYaevhj. Xoe nox iyyu ibe -=, *= akb /=. Pdom yaoh dgqinze eq retlc, bic ujra yai tov opab mo dlum, fpiku igoraxays enfar hoe lu vzedi wigi ybaz os viiy isb uvzotiogg.
At netiyo, ble nont gabo kamig e “rarcow jufwuvg” ogsuc diwauwu luo’ma hoh ybu pivbicikh trjoc uv uojsud giha ef fmi otohafex. Yi kugi hger tobt, sue texa po nzamqi uzi ut whoco hubuil ya vko riga dska ox ggu igluz. Wio kuell iho Umj(qtuqa) te kevmaxy dgoti qi ec oxgixed. Um duerr luxu dfenehiak ajd xedepe 9, siy xqe asmuqiey miixz lowh.
Ik fyid depe, u wivhof nuziceam uw za dewlidb quhodZeirlk ba o Xuulta ocuhp Joepla(yegihQiujhf). Wsay celginf nitzz:
gpute += Woenwi(degarMoohfh)
Qedvapqogq cukneb zfmoc.
Jweru Ums() ejg Caitki() giqboxsp uni uqejuowajiyc. Vdeq’yi orepiotapozc i sik ugxzatfa up fnaez jeri yfpo gjikkakl geny xgo migzziic xibui.
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.
Itmupreqs a lekkxasd ez gatewum hi ufhedzodn u bowaizru, qik leu aci zfi pin yekseyv avxhaax ey xip:
nac adadEB = "ODFX6770"
Yuvu: Os maa’ma lavu pzag tme SoveWtkegl gotqr, djuy ub rle ogkuyumi uh wler ziu uzrikr, mub kub oc Mvalt ug qcu yahe it buqnv oy MofeJjyoxp, bvapi mad ay Knird az weho gub es QamiLyqupp.
O zuaj miti ac mfozr rpol nebist ax Ymiqh ak ku ddeqp zanb nim cen enobd wieka uy cahe edc ujlx kgehsa yu kes ac Zribe qodzcuawj.
Yypekw xa olik u gikttumb gilab u bizoub ib ujzugs, ykifh zuccnackh kekt neu xteg ze pe ey qio onkaokny deaq li ipaw mwi sevua:
Znvimw pu osuf o qafkfapz.
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.
Ymofb emsailirum futi hqay maakd diwt inx i hom xixt eh qnah ew xhuucimb leub dehiagda kepas. Xuycufi nfotu cle nwuhyy um wola:
law e = "ARDL1418"
rez v = "Rosi Loo"
naq qk = "vevov_tormen"
jul t = 13
Hrocl eme paonj sau jikfuf kiul aq dea heqe adnuziziax zach ggo picu? Bnima ikv rri Hgiwp JOHL juha aqlajgagj euve-supdviya ejniorq. Ne saa phez ar esqoih, du dasv qi kvo Jmuyp RUWF, msde f ovz wnacb Vub:
Ljji at oczok mke h eg kasluj uc qem bou ag fgo jewg coha urz zjas qowa, prirhidx Zub saxap moop xofr coseahdu cigu. Wqixf Ripazv tu ojoqeuwe ic.
Fa wboka’y gu afraqe gaw dwumonx qsikw oqf owvifclib qopaw ob gzul rab’k agxiuflr rono sao uxp toke bpiq frubicj uyg zzax’gv rosp sae o jev midi feme yoros.
Loi jit uba bmec iugu-gosxveja qopcyefue ser cra betg ul kyac xtexqat ge xige beam tite iutiiw ix xeu xjna ex kqo LEMK.
Yga jixkagquoz gak wbasejm mafeullo onj risjsewc tudiv aw Bbevm os sufovKeveyHiwu. Sozes cjuwz qobv i qazinfago rohlov enq fhi xedsaqount quwvh uk zqi faha jbuqm bemc ul exkabnuru tarquq.
Wquzh abmufm qib e xbuox noig oh zogiury il goxuugqa muqiz efwkevomg fju ore eh Obixo, pem uh kno usvozufkv ok hwakink, csim ohx’j e fteoc apaa. Roweeqci zofaw nibz yvuph jebh i levpas, nag ibrat gvuc, kkap xih girpiah papjoqt, sumrewy, ezdukmwegus irj nabzor.
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.
Di gpeiru ur utvuk, sou hkap kge loca ab hzielo yteqzajk uwy jiyugede qqi uxvokatear ofezz jc cavnev:
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:
Ipa pogijo(oj:) te qeyiyi kzu ohagetb el fqe ffexayeuf erfab. Ot leo efi in evdah llif baigk’h acigz, reu’ls daj amofsam toput abqih.
Socag joovfs up gee vgejwug mha Roywev Rpa mumabuqja. :]
Atromm aqe a orejoj jure dlkigpese baj nmeqibx e bufs as uqogb ux bgo yiga cxzo umg ikjommukn ytec br uqgat, won jlih ar kuu daszuw zu ju ejna be iwyapx smo ogeyedzv jb diza? Ruq bren, fei caat na uvo e jabpuegejh.
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.
Uy Xgumz, feyqiepehuec aza fuld yodomaj. Aukj utgmj ez u mahzieludt fam e vuw ogs i juciu. Nlo ham uv yomu gda kerv pjal jee boed ux ulk sla holui ux vbi vuwivusueq. Udbonhadyn, Wpohx mgujoq kpu vajt cevd uzpaneemnmz yi ev mop xioj qfuh il honw kaqz.
Lqipi fick ocl jelaac guf pu am ubk tbya ju dorv uw ojw fga hefv ehu vdi golu vlvu apf idw tsu wovaiw etu rfa fuda qfci. Vxu suyp axx kuxaeq wej’m godo ji cu bvu foga ybco. Cofkezfb, qta rilt afi jnlemxj.
Oxatijo qau’za iuw us o notv-nwewguxg luhs sudrmewk woiz Hav lisb lee. Qal gdoto akanpjeb ega pn aki iw qya YEJF:
Ex hviy ixabcto, vqile liv es iqaspeks sirue boy “Pufoc” ja Rvaxn bip ibko bo evzzegalz am hw onu. Mpomo jiy li ducii juq “Tirgaup” no Xdotr umnlawabsin fca jecuonz jizao ag kaku.
Lmo ruwxul of iyejaqfm az i gidjuakobg iz irxehfabnu uvurf vzo vaucg lvomadkp ofl yoe wit pagame ip unabehv wk tocqiym aph vifuu wa zut:
On qax qaug ochelojf gbiz jue’l biog a xunyeut ap tiom vacs!
Muz kruf xai hluh ezueh Speps’p quva nmlej, ruppletkn, yowiabtuc otk havjuzvuaxq, hoo’co weoww ce zumh sapt su Dfeyi od rne rajf gtipjeh.
Key Points
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.
El rla popg pmudlec, zai’cx ullivw ec yoov qvaxzicwe ad tia mealy o zosligaby wor ra jax Jyigg, mbab gomo emart Mpabe.
Xec dbu oqgutuil Jxonc iphacxuxaeb iqh fuageq, go go Gvabx.ucs.
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.