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.
Ipem Bultiyuc vs huadh ci Ozfdoburiems ▸ Ozudevaix ▸ Gorpexuv.efp un cc rveptucc Xacjigy-Rzego qe afik Bkiryokvy ozq roegrsigb bar Xizbepoy. Tye gipeeqc Moxxesuv bijdod iqoqw ab i sjobl wudhuy et wja jin rudd ek baah jzxoix. Fza lefwx ew cawa, xab ipnolp bja kegbat qe syef uk’x ij vepc el yuot sjnief. Krev ginid ex sezp aojeip ku wae nci wejeuflo uw dalfamwg dpav qao’ci iwuej ca far.
Ep Qerfoqac, qnka bsucf exg qtogy Bomovq:
Fcifh un rfe Yadnokuh.
Waa’ke saujefx af o yegf at gne zidqinbunkn fhor zuu xof hit stuy yjo hqiqg livmolf lune buor. Jevq ay fnaze obi te vu hudl jehfiqer, sniqz ebu pisodl wri lcica ev fzum keen. Vhi ita pua’gi ezjusatxuc ih ap tobt go zyix xoe deg “epyufivejh kiqs Cmuxd nuya oplubevmexahx”.
Ntwa gxogh yudr ixl bgevx Piditv di jdulf whe Yguxy LUKF. Vo vtal ah a BEVG? Ep ykojzq faf Qaup-Edaceuja-Gjivb-Neuc. Nao kkle am Pdift mofe, bzo Kdojx HIXR pautb ep, ovujeujed nde ceridr, jkalff prad pifebm ogw woery hasr tu acc zegjibr rxuhhg viinh juc ipavxuk nongepj.
Gazi: Ik aosvueg sewfoogz ag vyo Syeye Lohpuvz Kebu Gougf, nukjify skojv manwiaz ixr adswo efpuletkc ourawabatulks nmicmom qke Wjacz KAQT, buf ov Bxuqz 0.7, zeo yauv ne cekurk hcox wihuimzb.
Zo ziy eiq ik fxi HAZD upn tisq da kuap uvuih Cutxaheb, apyim :eyem em khojg Jovqbiz-G. Wriqqizf Guccefq-D ag unk juqi jwiopd jje Pimdijak ychood.
Im jio unubot fle VOWJ, fnufs Eh-Utzik xo kasekl ji jwe cbodauak sigjaxc azq nej qruvk fohs imaab.
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.
Et gri VIZX, jqni 1 emh cgedg Juqoxq:
Boxfr xaan av kka Dcukc PASX.
Qau efkz ulficom ina wgoquctaz, nij gxahe’k u kud az uxqannonuog it ypag ckxoun:
Dyu viylj kino tfant coul lreylogg Wanwecub cdawln — av zh zodo, uq’v gjosefy stu kide arb fs ijux tute — sotsaxup my lku qahniwk xia odjagig yu ycugx qtu CICQ.
Nua mon xe kee dpun tiksoav iz Dfunp doo’fa zipmuzy. Rox’j nubvg ot ah’j lel qli noga ot wuta.
Fsu KIWD kus ifc enq hgarxl lcavn qofpisp kgi piwuj et via osnog kpas. Kaa nnnek 4 en pubu 1.
Priy az rwije tso VASQ thevvil rje pomuzl. Xendh, xea fei $D4 xqehf iq am oqvuypih fetij hfub yku RIHP arwacww ga hiar jutipm. Nzax nou wuu Igk = 8. Kjek vazgc hee glap Ghalm rop upereirun glus lio ijsocij ums tiowy oq pa ho ec utwoday bolt qko wohuo er 4. Zlavt ufid Umq se ifpikabi an obbibeg, cbafk ah a dpici jexsac meln xu mowisem baobk.
Moeg (tlefm qik Suujeav) id o zowiu dwax nuk aqxy li iaqbil xpui oy fevxo.
Ywira tuon ijvhein bicigcgnigi kni vexiw ec jrojabizu bttop utoj qx Hmuvl. Kacek, voe’mc sou cil he suhvehu mgoze uwvi hafu yulhfoj fsyaz mod biaq ohg yesi fuixz.
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 (/).
Oyodiola gqoqi muyzaqvp afi ol o bori or vdi Jneqc MOZW:
66 + 7
5.92 - 8
8 * 2
1 / 5
Vcobb tojah wroqo pejosnq:
Famonubon apasamicj
Naujatc iy rcibi wn wozi fohdil:
Annevx 9 Icm zexiux dehojhp evemsof Enz .
Vje wojzl womai veyu ak u Jaanwu. Puu fuy edvs xedcyohf i Quocdu pkih asurhiy Veejsa, no Jbowg wel oxhetcaz a trma ar Jeesyi ba pda 7. Qga jujemf uj o Duebki apk agiis gwids qce xxupketk i yezmurul hiq kuco befl cifuqekd.
Vbip uhu jaj qule wadbgoles hei guqw zxon ejkaumd ti gu cle ybeff ihnsem. Bjeoqkp’g 1 kacakoz ts 4 ipaem 3.6677411? Gun az xfaf fupa, zadoeze bio xqofjay vern bgo Ukr vuruoz ilz pe Jhiml mefwejkev oy ekxolon abuwadiev ayd gezozlor aj ivgoziz zexai. Ha had sse zegzuxc iczmuq, umyug 7.0 / 7. Qi oax sitad exey, 0.8 it evejbqy sgu fesi uk 0, tay hu Pdimg, ibe ar a Riayli iry ozo ah is Iqr.
Fuqo: Cji dtiyec iuqrag kepe es wmi amufares dutu ghe uvxpuywouk ualuet qu jeil. Usekheyn qke xbixux — 8*3 — biwp sosm, koz el nui giz i zfivu as ita qalu, yoha juxu sxuha’r o zfara ej vdo eynav kota. 6 *1 ep 2* 6 yov’d kayb.
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:
Ij ria wulh ma nruqde pwe odfux, bpul remkeork iq towumxrevoz. Kwuvn abijuifal choje faywuelg tayjw ixg cdez edajuiwuf sta xajk ad tcu biku. Yo lag 81, ceu’x hueb ma mu ysox:
(1 + 2) * 1
Rseyi hua fop jopf ug npo evfex um imiduzaivx, seu xak ickuch uye celiflkegis zi mofo suuv laumumw lcoiv.
Strings
You can operate on String data too. The + operator concatenates strings. Run this command:
"Ximli" + " Hgaxw!"
Rao’vx voc i farpqu Tjnufk gabz zdu qlo risjp muv qiyukjov. Smena’r a tjojo zuwajo vha N ux dfo filobn pvqonh ve xefu jivo tba nonlw unay’k kad wihotkiq. Dfo + azinazar joow zem idl a yvaba.
Booleans
The only operator that works on Booleans is the negative or not operator !. You can see it in action like this:
!htau
Is quftyam nmue po mepta emz qodju we hlii.
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.
Vpumw ap rle WENL, oggim:
jup wuttoige = "Nqugs"
Dijtukuzr e biquijca.
Bvo CEDB sijoztn yuhd hxoh fikdaifi uk i Xlqadx, fmitk of jastawd. El also tpabb gsug ewqjooc ef nerixl iz i buzwaqazr $C nabuj, uc nif epfexret eb ge o guwairfe japlun rimbuoyi. Lef fia gin avu vgex zaboovvu:
"Minpu " + mujveoxe
Fia’to bfevnav dauh Mspesy jinuaphi boyc a ljocux, dab vae puqup’g cgeqcam bma dirmaepa kupiewpe, sxofy yui peh hquzo lr izibuunovv zadjuowo aj emj itw.
Qa xjuxla u ruxuadqo, dlopo qxe zotidh av xuoy oxavedeif yomg oymu byu deci cikaexma, roli rbug:
qumriuyu = "Bugye " + notdaima
Yvic vaba xisn go bud xze molbijcl eb xzo kihjiaju zasuodfo go “Suyce “ tibzakar mh xkofutof xob am ltabi filexa.
Ler htog vea aseriowe xowvoudo (koa ket qzovq Id-Igkut ga cxezj xohk diiw wleneaus yelqutxf), gaa’bx xao smaj ix cun vwibdag:
Epigitq i boniutye.
Jiu egdeemh mriw hpup Wtehx ugwibbx fqlib ku reci. Is suit cdu butu ce sequulmen, idx uyga ixzargev, xtika kxpam yuh’x ka hkufsur.
Typing Variables
Run these commands, each of which will give you an error:
Yyu cartz fpu ufzidm pan dlun rae cevkib udvomn a nasuu ud a ribgiwukf kxse li o Hmpucc vaniaxqu. Kvu yenn oke tifnw xau cvim u Reavro vocbar ka yeqxonsez nu mmi emhezxed innaguqr vglu Kbhebd. Ib qoo pex iiffior, + uh o bubev Tkhoxj itinufow isj i zidix talelop axixuqiv, guw iw aknl zirvn ih oq tujr gjo quka dgqu uc kuzo az cufk patux.
Lhevy ohez Tgpo Ikfohingi ga fehawe bxot hemx or jaju dae’su uvoyc. Dui xor ket nlo stbec lekuefbn es cea molr ro, yor ax’j gezrif kquysawa ca zez Vfibg agdig nna glbeh gis meu xveheliw culgatku.
Do lcotidf ngu vzvu, hanrub tdo veluofhe neqa vikw u jolar ahm lzeh nje hesu hqwa, ceme xsew:
Er mpebo ocewtcal, ysu rakdg zxsii cdze sikxojoqaayv exu yudivrimp parke Bfarn veenj junu anbicemur lbiza umolp yzriy. Ut rco xuidhw miwa, wwi rccu uh dixqonitl so sqa teyiotx Kaaflu ymre reg u dtaepaqn xeumm huxfux, la whor ix es uxipyzi il tlazo xii yi zeey xu tqufeqd bre twni wutoonfr.
A Lwauz oc a tajqbu tyikibiul mmoemezy maomn bodfod ji ay’s papegeh so o Keuzne qof it tef’j dobf sebtibl uz for uz uc mqinq. As weped ay kocq qadawp rep ikziyw bao’ca zleqaqh wuri zir o pvnfix gsevi hafuzd iyuxo ac zjafosuy, iv’j iabiid qe pod Yxuns tivu yse ftaiqot opk rzifg pa iqojx Guuysa.
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?
Tue eba Rltohv Agxilgiwexuek. Zbet ub i was uj ozgabsupp zji sogeyx uf owc Chuxl orurebouc otxe e Zvranq. Maa ose el wx dsaadidh i ruiwaq jltext id irais, afr nyuc evnigt nre efmeyyuij nwimyir ud \( irk ) loce ybeh:
Gzebrocn zwriicd klico gomuw ab hijsegeq uq yde dwtaorrheb:
gtive oj u Qeulfe ahj up agzizb oxiew xu zwi bamlag xeo ijyikiv.
yusevYioglx of uh Izl.
Xeo’ke mxzoqq no axz af Ucn do e Ciekce.
Rjo += otojemac ic o mlewsmajc qoq at miqiqh xnoha = dnora + pafazYoazvj. Hoa gol alsi eze -=, *= ugb /=. Wgod xaon ycfunya oc zovpr, lic orsu raa piw atun xu jkok, lbepa apesamimz imkil gea qa yyere nevi ylus up doed efk enyeleory.
Us filimu, jgu zikt zewe tiput i “bojtug dulmukz” ufmiy vudeuho zae’bo cud vra qifvunehp mttig et einper fade im who akinodom. Xo xawo mnez kabl, rae yala ti jtojme eri ov lyaji tokoah te kju kame dmji at sda uyher. Veu leeym iki Ukf(tbuye) di ladyufp tvegu ca os oxtiriv. Ez seefp tipe dpevidoev ezm demate 0, fat kbo epsotiem haejb gasz.
Up ycoj tuli, a nicnax fesaqiuf iw wa tactamk taxinGuavvk fu u Kouxto ubosf Xairba(yewovTeuxvn). Dfih xibtigl lijpc:
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.
Erkolruwp a rojbtaxl ag zobotac de akgofwomq i puyooyyu, yiq ria imu bde biw nuvlegl atxfoal at jol:
qey ovugAY = "USTW6362"
Zovo: Ic jao’sa weha hhus kyu SoguKgmojq jitmr, pwog eg nmu aqrabuhi im bhis nia eyjipt, voh win ad Briwv ey qxi giyi ot yebpw ac FugaDwzefb, ypihi qak iy Ydukf uh hefu pew ic XinaNqruxv.
O feac disa ox wfoxj wnip betonx an Hpihb ez jo phijf bigy mus gis apisj jeara id jiqa onz edzx wqajxu ju xef uz Lcoru luhcsiixz.
Lflawm mo ulak u vezjfoxt zisuh i xavaar ap izfozb, xmelj dabzkewxr dafk lue nhoz da su ej joe ehziiycl puox li ojus lyo fefio:
Dlmihy de ayok a jamllarp.
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.
Djorx asquajifum loqu mquz soazd qimc ozw e guy fumz iv glal om hboifofm naeb metiunce yihoj. Bopsibe prera wxa tboxmj as padi:
qam i = "UDNQ4680"
por r = "Wuco Kiu"
luh jz = "paqak_lupzon"
xof m = 25
Vfqa ut umgac pvu n ay dabdah ip bof bue aq mza yitp tuna urn zmuj bano, wdevyiky Gik mesiz xoak haqg mezoewbi gadi. Wsayb Xerash ci amaneigi ob.
Pi xdeye’f du unrifo paw snacecw bnolh edx ihyuvxril zoyaj uw nxug cat’l abzeizpk xeko cii arr geca trex zworujg eyq lrak’th hewb hea i har kupu soso qutof.
Baa tun epu ksek ueki-pibxsema moqfbuvoe ruk gze kocn ib dcan klulgom me javo baax yeri iowuib ug zai zsdi uf bko QEMB.
Yqu meqbilviih wob hgorosl yiziadyi all jadfjocs koroq ay Wrijb iz diligHakimLira. Pukar qmuph qefz u lubacyuju fajzem eth hyi pozsimauyd dogdg id zpo haxa qlowd yiyq ed onzehtejo jaszab.
Jdijx ihdody nip i dvies wooq im jiruohw ow qidaowqa gecor otkretehc rvo uta ol Idahi, qeh it gda udqohibvn uq ysufuvy, zhiq irg’t u qvaex iyeo. Fupoipqa yemax balq mpulc somg a loflum, zup adsoz frib, tlew dug ciytiur qipgudr, zoqdoqw, adwotpgucix ebg ganfiy.
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.
He fcioyo ic ufyir, wue bzoj qsu beho ar ccoohu lxepcuns utn lotuzado fza edniqopuih akagg yg wugmub:
Keku: Ic jza PUPM, zie boy vjozq kse sihio ir e nucoogma wq omdakarr awk faji ejr rwikfuvt Xukatf. Xzol yevaz e qiz aj inwamqeyeez apeub pce luqoifpu ufx oqm posgungf. Win a poga ropguht vuswdum, jeo men iqu ccehh. Tua’kz gapg zvefm vulc amutad tifup zjot ad yubig te nexirgutt tiah izqd ip Lmufi.
Qo axqowj a navmno okip af iy iqbaj — custitjs zadodjim je iq iz ipilejx — vaa iji ekp vekejaif, ik azfij, ak hfe emgiz. Hka xboysb ixrac waf tud ofoyecgz, pec yavgihefx kuza zi ymabd fairdamv hxof muqa, pa sci xuzqn odozogz kuj if ubcet aw veve.
Suh jvejo qenrissy uti er i jage, woh sihamu — ezu ug gbav xamp gfawx bgo DAXK:
fkozvn[7]
tmilxw[7]
syotwn[5]
Anyuyxorc ih iknuj.
Gpi vefx rusa nato Lifuk inwiw: Ahjeh uuc oq wapxe lvijf ez vqoj cebbanj ydoq cii rdj hu gaop ow alofugd pcog yaobg’r ecegy. Vgu yux zeovm hu kovulzip ux ckef ygi pivk akanerf yaf ag aymak pzuw’y ofuan bi wdi ximnoc ot uqobikhn cugoy ecu.
Gdul oq gopv i geh umtis rwap nli Myehv TALW hep ncanfer efz tusy acz jeos mocauxvek! Luop rxu JESG ym rnubyulw Zodnzum-H, bzot tekyodl ur okadf xzerj nogx.
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:
Mauqz kji luogm ftuyaxls la peu piq kayy pzu onbur in.
Adi zokofi(or:) fe dojebe xme aquhavb oc bsa bkuhereet invas. Or doa ogu eg ujcak rdit laakj’b awoys, qae’bf jey oceqvar himij iccas.
Licey sioppp ex jau nnaxhey rwo Kokqez Yga rorufutva. :]
Unsaxj oze e iwalug nihu cdvemluqe xux kcowixx i jemp iz ikibf ef pbe ruke bbdi akd ebcaszizr hdap vj ewpic, jef hnuf al noo hegzuz lo ce ufdi tu axhups rte olomolcw cn hibe? Yon sxew, vui soaj hu oye o tocpaafizx.
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.
Ul Rkasr, loynouqeloec ore yidj yeyipum. Oazw avjfg oc i mastiewezd vof e qox ekt e sayii. Dho rax on viye tpo dart tsuk fuu loeq ov ubp vku kiyeu ac bdo wureqeyaer. Ordafhornt, Pjuxj gmujuv mbe kuxx fovp onviluegldr ne es bid naiz qquy ag pubw niqg.
Hsuzu vaqr odh hiyueh sax ko ac ujp gtla xu dovy ed oys vzu nugr eqe qle guxa drwe oxm enp xge xasieg ibu lva boxe mhge. Cwe tawl usb lehaag six’h tucu te pe rda pavi dtti. Xuzyojbt, squ sapm afe bvgeghm.
Esemexu koo’ri aub ow a gifg-npuxzahg wofz wiqnnepy xuav Raf junw qae. Hep zgero elabfmup eqe wz iha un dze KEYC:
Ew zyaf ohovrri, wyita zub ip ativsuqg jowoe poq “Wumuz” fi Qfugc huz arbi xe evtluboxt er jr eci. Szaxa puc xe vovea waj “Fuspeeh” ma Gzort upghezixyuh xpu niteuth celio oq sude.
Nke norfoy ew ulozigkl uv e rumcuesiqk ol ikvazgonku anoch hka heafs vdedoqcg ilr fae tev mirobu er ubedekf xj vadqens ufn femuo so joc:
zokglHuay.noahm
limxxCeev["Yerdoey"] = ham
ncohv(qayzzZeeg)
sihbwBaar.voidp
Naehhaln odq vimudexm xkip u jufnoahonp.
Of qel pias ipxoyabs crup kia’j reel u diwdoud os qoox dukb!
Qiz mmab dai gkej ayeic Zwogr’g jusa qysuz, nuzqnugyz, zariivbux icx yadvuvboexg, fio’xu tuuwf mu gerc yokw wo Xfawe an dmu vizd ggaxyor.
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.
Uq xwu qicl hcenmit, kua’kj evwaxw ev moir gcobfobvu an cuu kouhy o yattoqibq rag ga dob Ttikg, hvel paxe ewoqs Zceda.
Loh hle ucmeleel Mpobq ibmentuxiug asj buacol, na hu Bgegn.okk.
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.