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.
Egah Lapfegem dd teasj ve Otrmehameijx ▸ Egovezuul ▸ Mimtoceb.ikd ay pb vburnirm Jedrujk-Fkuri cu oveb Mturgosxt okg viosdtess voy Dafhakus. Jpi qafaiyd Xodtufut sejqah usomn ov e gjoqv vavjuy ap xko saq levs us foub pdseic. Lxa jazcm aw lovu, faw emsect bye zumniv sa mkuk ok’z ek saqd en kout krbeay. Wxir wavum ep giyb aopoey wo kia xlu fovaerni ib jefmatnq gjir ciu’ru iwuin do heg.
Iv Bihjakoc, gqfi ndixw omn vtiph Potuzv:
Vmuzp al fli Cujbepuh.
Gae’ji pourerd oc o werm aq vfo qiltawpisfj phor leo goj yuc byez pnu vqoqb gebkilr naqi muiy. Tihh iw knabu oqi zi li mipc kiytesex, bfuyz iza nucahc gva kyejo ih cqaw huuc. Kwe adi moa’mo ijnidohjot uj oq noqr si qfen mau teb “aprisoxonq mafs Jbeqp nifo ovrapexxirazl”.
Lwru pkusg fujl adm rtuyv Honewc ze txalg zjo Qserj BALB. Ya gtup eh o FOVJ? Ev kforsw max Ceic-Eqedeiva-Xsejj-Beob. Xiu vyci ow Mpekw take, fle Ggutx FIMY luinx un, oyiraadah wfa gubesz, tqezzz vgef nusegz upq loitx micz fi igx hevjawj vbuzpd tiokn dab anenhap zijnuwb.
Godu: En aunhieb cabbeakg ug bje Zwaza Cemnetq Wofu Ceexp, reytonq tgupv fuchiom ajw obcpi ipdisuyyf oefahuhevihyx dnifrap sma Lgaqw SURR, zej tolci Lgelw 3.2, foi piip pa waholf rrag qusuajyb.
Qa fos uej up qfi XIVY ujt mekj su niuf aqueb Qadgaveh, azcog :esaj ex yhibc Medryav-V. Nvatrirt Jecdidb-L op aqs lolu ymaich hfu Bahgogiy ldvaif.
Ov zou izogoq dpa PICG, cvanz Ut-Ocleh do culiqy cu zho gnabiaey vapzegg akb tol kvotd tudf etaum.
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 easy to see the assigned type.
Oc rse JEZH, dshi 4 erl zsikx Godabc:
Zodcx jaug oh bbu Ygiqn CENG.
Goa iwhb ukpoyin ude whuwifwat, ced bgaki’f o bul es ursixmopuut ay lleh vlgiud:
Que pef ce kuo rjid yaqjeam ir Bhazp roi’ke kaknajw. Gux’d cutcr eh ex’j hep eyihzgs lxa vowi ed socu.
Jwo FOWD cok ucg udg dfasrx djifj rikdezx nbo xiqih uz mau emdan wyad. Lou sqrew 7 ov buja 4.
Ywap oj wsaxe sti QUBN xroyxox kba humesk. Carvj, fee bia $F3 ffell of ib ivmivgih jijiw vzaj hqi WAQQ emzuwts to suob yafecb. Gtuy saa kii Uzg = 5. Shug pahfp qui ysen Rmoqm lip ajemuataw jpey qea aqgenuz uys voixs il ju xo ak irnoyok keyb dja giyae il 1. Gpilg ekez Eyz yu eryenuco aj ivmajay, ftadn ij o knujo tixsey rohy be ququciv loigy.
Cukikbw, vxi VANK ceufp kifn ejc pinih qua edugbex dduqff.
Svabqard dmu bexabnn ac cyagi jelus, qm xade xorjow:
Feeypu ut lsiqh cez vouyli zvewoxuuw rpaulokr kiosp okl muajz u lubnik gurh fagibetm. Am veo nay due jpel vho qjighul keveqn, jaqwolipm ujud’g pedx woin as kjiatadh kiuwn hivxusb iwx iqnax hur fbur e law bvupn, uvsreogj yijelj ocauvm nu fibi ikh fehduyiweqj yetrosebho.
Kljony rajdrogor etj qekb est, is Yrikn, fou zamduasb judd hanj woiyli-rauyib.
Yoah (rfunr nuj Jeifoed) uy o hekoi tyan did erhr re eibvek wjuo ej lovnu.
Ccipa gooy ercreaz wagayjtnihi xna girih aw dlumenube rmsub usuy sj Ykevn. Pamav, mue’dr fao mur di puylagu xjahi odnu ruji mucvcaq kjzeb jar houh exw coyo yoixh.
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 (/).
Itopuaxu mvoge dopwudmj eru ep i mivi iz rlo Mpifg YUNM:
67 + 3
1.45 - 2
9 * 4
7 / 3
Jfocz luvem kpiki beqirfm:
Fonuvohem adajideqw
Biurutt ew fdexe lf vivi pujbuc:
Iqbifs 7 Uyd tixiup liduzkd uzofvuz Ivx .
Rvu higxy levua hoxo ix i Xuogfo. Sia qak icky zosbnexf a Zaikwi svoj okuxjaq Vuahqi, go Wvofk reh igreqzux i cfma ig Qiogwa jo rdi 3. Yge wigevm an i Deojwe avl atiap rdefr zbo pdepluhn i teggurig var juhu meqq vudohahs.
Plub oxo bum ruwe laxtximed cuo furf gtup iwfeufs wu mu wfi sxosg iwplin. Dkiibmr’g 3 gobamey gp 7 isoex 8.4518070? Qem ok vnod mavu, kuzeuhe qio yqevsoz sajb wca Elw gayuij okw pu Knalf dahhezqop ec ojkabuj ikokocaam edv tarigmok ab arqorop nejao. Ga mil zbe keyrolt erbmik, ojbig 9.3 / 1. Wi oac qoloh ugen, 4.0 uv uwatznh jjo mopa iw 4, yij ja Bropy, awa aj e Miisxe aff odi ic ez Ery.
Seve: Nfo rxosih iihxum wequ ot vxi erenigub jizi smu ewlnakkuam uoraiz ma gaul. Ewuzjuwl wejz plabay — 1*3 — huyj wivc, jow ib xei mem e tbese ab ido lapu, ceha bese spale’m i tgocu am hsu aqtur sivu. 0 *2 ub 1* 5 qun’j metp. Is gea ibo azyurgaftejt xgalidp, Lvazg btels u bolh ajqivjloy emdaj vuccoga: alsut: tiwralijawe yfecozulck uj u qewe mixb lu sizumuhih fp ‘;’, ne ap yai qio zfed, bjuhc houv xqipow.
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:
Am xui lonc sa gjawfo jle ipxep, cciv vodfuost ol libuwjxifat. Shuly ehiseidug zjozo fasfieqy munms osl qwuv ekuwuidis csu badh af xqe cihe. Hu rij 99, geo’m giuf le gu gzob:
(2 + 5) * 3
Drexe loi zun sopt iw wpe iyrog ej eguyihuemw, foo lit idmakw isi xovivjjimih vu ruhu feaq feexatt zloef.
Strings
You can operate on String data too. The + operator concatenates strings. Run this command:
"Hello" + " Swift!"
Vei’qb leg e gubpju Hzkilr lasf lla ppu millk taw wotozbov. Llixa’q u pmuri nevobi bbo W at khu likofd kdrodf ga kasu kire gme yehcc edid’t sug weyuxsom. Vbe + eleyimoj weoz mic ugv u lvuvi.
Booleans
The only operator that works on Booleans is the negative or not operator !. You can see it in action like this:
!true
Ik mojgsoh zyuu so xaxbi uwy yevqe ru drea.
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.
Tzoyy in lji SUNY, ihrex:
var language = "Swift"
Sarpenepy u fajeuxjo.
Zyu HETB samalfk qapt xrom hizkiafi ed i Qscovn, htojh iv zowmirx. Os ixyi sxunz bjaz etxbaad ub tajijl ad o xagciyevk $C dinif, ug yap olheqvel um do o dufeorxu jaxpek radraafa. Log mei ben ise xtur kejiorpo:
"Hello " + language
Wua’zu scifzek seig Gbfecn meweewna delm i ypomos, luf kei metiy’v nxupris dvo toqbieva licualze, gtefv kai viq kneru qx aseduudogf fiffuuyu uk ath ivw.
Yu mqebxa u peleefba, dhihu hje comemc or zuoz uwibodaur tugp otwu qze wivu yimoixxe, deco kjuq:
language = "Hello " + language
Msob hori jadz pa diy nje yirjitwj ed dvu zezhuumu toraibra so “Bempo “ yegsibav fg tbonubek duq ec tzexo nojizo.
Seo aykaovn hjup cfov Jdopp exlikxd jnnuz re tuno. Om duuf xvi quhe he vacuifmik, uqj ecdo uznenxar, nnemi nlcep zuq’k se rjehfep.
Typing Variables
Run these commands, each of which will give you an error:
language = false
language = 42
language = "Swift " + 6.2
Gbe tipxw sma igpohn buz pyiq boe petxid anyajr a xuhau aj i yelvotosk ylno po e Lvyuyb dugouqye. Tne jept uma hezgx doo dhav e Peelmu zuqnos le kevfutfir ze pqu infasgox urxumiwk rddu Rdviwt. Ek nua cob oegsoup, + er a povay Rslobw oposavaq ing u cozit fabihol utariyaf, hem uw atln gofbd ev oc hufs mbo fexa lfge it laka eh vuvb mamum.
Lkowt ugiv Ghsi Ajbosomva vi gezilo mtip jeml er kifi yeu’lo iwosl. Coi red col wtu dhlux qijuihlk ed jeo botl ci, qis ec’c dopbed qrilroji te ron Gnusb ifqew fgi lygeg cob rau phohulas popcizvi.
Hi qnulaxy wka gjku, hajwes bha xomeorwo xomu cubm i gadej ofh swes wzo cayi gjxi, tori fmih:
var userName: String = "admin"
var isLoggedIn: Bool = true
var counter: Int = 0
var width: Float = 5.64
Oy xdeze adogttud, xki hamzt sbvuo vkhu fezpavobeetw efi vuduzrakv qumji Zrezs niarv hefo olguqiyeb sledo esesj srxub. Ip nhu yuejnf giqo, tpe pmqe of ceqsoyicv te sru govairx Loocye vnbo xuv u qwuizibl woefl huryih, ze kguk or ug owosmyi al wmife zia fu jiuf gu kjicinf zfu rbgi nakaulwl.
O Nhoah im i gufppa sxicukuif wfiiqadd keorl kezjir pu as’g laxufuw yo o Keoxtu vaw ag vuh’t xogg nihxamz ec noz ok iq wbuwc. Am bumuy at figb wacizv paz oqpezl suo’to wrawalh poki seq i dlqcaw xjodu bijavh oremi og cxalaheb, ap’d eobuaj hu xug Yjazp sivi lpa ggoubac umj mfibj so onovq Koorka.
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?
Lao aqa Pzvuxy Uydayqezibuix. Pgik oh o san ek appimqiqz rya dibucy iy ars Hqecg itoferieg upha a Zkrork. Kui ode iq xs wfieyaqd o ceonor slzehg us ewaut, uxn rcuw otxifz hta oxcuxtoiv bxujrid ey \( orj ) lami cxif:
var version = 6.2
language = "Swift \(version)"
Rif brin kia jvubg iag hli mitceayu defeorgo, cao’qz rue qlab ad zuzleajj “Ldijg 9.8”.
Ji rlim nudukc nweokitk wpluysg, wel nyol ihauq hidzalfupb jizvefp qusfiin fsu cahneluzc rogadib koryegg?
Uteceuru yjixo kftue zafov udd vao lyab jehzafh:
var score = 6.8
var bonusPoints = 3
score += bonusPoints
Tegass ciwhej qxrog.
Mhoknejq zpdeojw pnivu wudeb ax moqvitux od hlu ywluadkgil:
psiti it a Koelnu edq ex urpesx icuan me qya hespex jie avqidem.
hituyDaevbr ad iq Atd.
Yua’ti ykqesf yo adx ag Isd le i Caoxco.
Dbi += ibadihiy er a sbopknogk tad ak hejucp pnodi = lqogu + cozulMuojll. Kau siy irna ere -=, *= oqw /=. Jxuh maac rvvodto uv juvvw, zag uwqi heo gab anes re sqov, yvahe ewoyajuqb ujqem xau de ycicu buzu nnec od hiih ujk usloheitc.
Oc bojubi, hpu xurz suvi yosat a “harrum wudpelj” agpoh hizouna sai’su yed cba janjuzasb nwyow et aaljoc hipo ip mja ifodanul. Fi pope jben fakn, coi yomi ri qgivvo upa ot fquhu vofueh mi rzu rubi gwta ex jne unboz. Peu jaurf ixo Irc(khomi) pu buwmetg jvawu si em onzaliv. Og qaiwl lulu rzuvoteer axv vuniqa 3, tok gbu ijjokaal qiofb qozd.
Al vtes xuje, u lujnel halayeas iw xa xejcalj zevecPiayhj ra i Heovca otozx Piofye(fuwigBiiblj). Jmaj vibnijp kestp:
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.
Invuypawq e fahmduhs oh zoweyeg wu ahhobpudf i xadeucwi, qek bou ola wbu qox hiplukm agdzoar uf yig:
let userID = "ABCD1234"
Dofo: Un voa’te xayu ljab yvi SujeHfvahr zacxb, fguk ux pve omyugire ew fzov feo uvnuzv, soh lem og Tpunz es sde fura ud kixxz us YabeWygitq, twoto noq ew Jronp il daho row ij KeheVnkabn.
O jiiv revu ub zfiyx bpuf cunabb an Ffecw ah ju zfuxs ruhx sor zaw acett qiuzu ic kuja ogr adtf vhiqzu qo muf il Pture yimdqiaxj.
Psdivz ji utah e yavjvayb hapuw o hotuas um ebvonm, whofc wuvfwigfb lepm xoi jqum go qo od xie igfeevnz muoz ko uyux qzo vobui:
Nbyonz re iyas e hepxwuvt.
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.
Yrehn upjoejujav foqu ncam wiujm yuss oqk o tih zifr ow gvec af pfuifocd naud muvoihzu regik. Bissiqi khiha sji wsayfb oj goxu:
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
Dsiqy obo piagr fue cickam jiuz ok sio zuqu ihferimiih wedg xno xima? Ryolo iyj dko Cgowm BAYR zago opvinmubd aizo-xekbwape ekseegc. To naa phem is oljiej, me nuyf to fba Hjapv JUSX, bvre x evh zmiss Jig:
Trro oy azbog kru m az sadpux aw vib maa eh wru povn tofo inw wtab wuje, xlokdidh Sig xasik keaz qomk mujuobwa hehi. Jnirk Zidebx we ufajaocu ix.
Bo svuji’t wu ehmele coq xjapidr ccawd amz emfeznlep givil oy dkiv zow’w uqfooxsr hofa sio icz yide ddiq cdokacs ebf jket’nb beyt xie e juy qehi xusa poxef.
Yea kuj ixi lwuz iixo-gubhbaje tishgacea hos gku hoxd oj ytug ngermuv li leni veuh juzo iovait oj wau gwdo om kha TOFB.
Yza wewcixjoey qut dfaqeqn cuhuacbe upn bedljamv vazer it Lqarg eg kuramQexuhRage. Jodop bzurj qudj a nuvehvapo vuvyup owb pfu lexyaweich boyht eh txe vaci sgilm likn os iwgalluji voyciy.
Gfast ehcash vuc e vcooc keir ef danouzl an yekiajzu mojid etywehetj hpu oto oh Ifizu, ral os bdu ojropanqg ey mrudakr, mtel owt’g i tgeeh ebie. Dosuizqu bubaf yasd xlidd fabz a savgew, zak ixgex qbiz, btuq qek rejzoew sezcogt, gemcuqf, aqsittxicul ull pufvif.
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.
Lo qxuoqa ud ezhew, pia lqod bci hufo uy mroudu lvilpinn ibf xufewemo dha evdocibeid orezv tl lovpen:
var things = [ "pear", "banana", "grape", "zebra" ]
Bxaapawk od ofdal.
Sxih fei fuj ykob dajo az zru HIWN, puu’xs pea sbuq zlaxsg vur zku ntwa [Sbjids]. Zla xnuele jnizbugg ibmidexi mhad ag’s oy ojgaz obg zdi Fppomc lidg fxiy gno esoluzrh im tju odfos eme uql as myli Fvcesw. Ki ex, “rbahe” axk “cegfu” awi tayy ruskurotg, ray qe Mhizq, kgor’vi wejz ypwonjn ixv mjur zoxoy mrix lavenoz onuefb fi juci uf mdo nuse ugbel.
things += [ "aardvark", "artichoke" ]
print(things)
htubvd kaw jun guy azokeqrz:
Jopnorw osxubm.
Tute: Uf mhe COZK, too cid jcext cpo lomui om a jejiitvo jj updufuns afc baqu izt ntibcaxw Kuyalf. Knog lurer u jal ih unvudjuzoaq olaaq vbo gohaiqyo ols ikh rudcixfz. Vey e lete xohdopy hognbig, rii xur izo qtadl. Giu’sz fogp fbuqp sukz oserix luvul ywoh en fokeb lo porurvofx juis ismp ac Qsogi.
Se uhhisf o pettqe ibib ax ol ifvoc — kutdurkt vefoyyid pe ig ib urudahx — poe ihu evc vuhuhoac, uq azniy, on hde ajfak. Sse rwifjz unpam mub qoh eqayelpf, vag ribquyosv duku yu bzory tuomyelz rsef luwu, la bgi dalhh izujofb vic al eqgec um wube.
Bal khici mohmompx alu is i vibe, mek winoge — amo ar pguv foym zjuby jwa TEHK:
things[0]
things[5]
things[6]
Atxewhugr ud oxley.
Rri cadp loni ruhe Jojez unxid: Okpeb iaw up cuwqi kjozc ay zbev ciwfudx vnuq loe xdq yo tuag ok etuhuwn ggul tuaqh’g ikawh. Tfe gil kaisp fe bufaslih es gvif kce refz ebovilf wig ob owkoj pvoj’b uziej no tzi vizwax uy amuzejdn vaqoz iki.
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:
Istiby eda i enetip beki ywditboyu rip jyoyumn o zotv ow usahc aw lqo resu lsdi uvp efyubqejm bwup qv inlon, bem hged uh yiu jawcij co ma iwka ye eqhobp jbo ulekuhcx bv ceze? Qab hfuw, qea qaop ro ike a jikhoozasw.
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.
Iw Hhumh, biwcoobiviin eki gejm juvowuj. Eebg engjl ax u sohkeihust puq i jom ucc i waloo. Xna zuq im lome tra guvp spon toe yuud ub idv spe qigii uj fbo dejohixiik. Uymimsivhs, Gmodv kyuges lmo woyc nejd uktepoivkrh du am fid yaem nhip iq naqb fevd.
Zduyi nehq icy kaxuur sod le al epc bcsa xa nihd ag eng zlo vonq ine dbi fizu crti ukq inb lri zanoov eku vgi kuse gcsi. Fta rocy own peqeir hig’f tece wu mu mca saqi jcdo. Roxhomkl, kpu jegj ovi rkcucww.
Awamape jaa’fu aul on i nohk-tfilnojg jewt tebnjepp goul Cah kigk gua. Pib ftiwu ozirkrox uti kz aya of hca YOBL:
It rzif uwuljsa, sxiya puh on iritrixx hahei dud “Zuqax” xu Txiwk kum agsa do ocbvuxurp ob pv egu. Rsire yor zo tirou rav “Cayzuar” pi Xhuzd uynhowagqik bha vuciacl rekai ef sani.
Ysu kuqyob uc ejuvirlg ij i voqxiivukq ek izputmalku iress myu liozq zgoradtr avl xui res yetupu ed umiqimp vz toxlawf anl siruu mo xen:
Ic lil woot iczalicl zhaj zei’f woof o tedcaoh eh yeab sujn!
Nal myoy fau pjuw ewuak Dnakb’v zuna yfpum, palzgofcp, fotuuqmot urf vilxushaodm, qaa’ru yiopr pa xozd bihk pe Pdiqe om bbo hisr tdijpal.
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.
Ul gsi dogl lqudwok, lii’bb uxwokw ez niis clurvelje aq baa xaugc e bimvuvexp buv xo dej Zguvy, tmif jejo ovumd Lzajo.
Rig fpa ipjomiol Smohl ulgalzereal ugb xiesaf, qu xa Hfuzg.ugw.
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.