In Chapter 1, “Introducing Xcode”, you installed Xcode and saw how to create a Mac app from the standard template. In Chapter 2, “Beginning Swift”, you turned your back on Xcode and ran Swift in the Terminal app. You learned about data types, variables, constants and collections.
In this chapter, you’ll return to Xcode, but not with the style of app you made in Chapter 1. This time, you’ll create a command line tool. This is an app without a graphical user interface that runs in Terminal.
When you ran the Swift REPL in Terminal, you executed a lot of single line Swift commands, but some Swift blocks need more than one line. It’s easier to edit and follow these in Xcode.
If you’re already familiar with conditionals, loops, functions and optionals in Swift, work through the first section of this chapter to learn about command line apps, and then you can skip ahead to the next chapter.
Creating the App
Start Xcode like you did in Chapter 1. If you see the “Welcome to Xcode” window, click Create New Project…. If you don’t see that window, go to File ▸ New ▸ Project…. Either method gets you to the template chooser.
This time, select macOS ▸ Command Line Tool:
Selecting the Command Line Tool template.
Click Next and give your new project the name swifty. Command line tools are traditionally named all in lowercase and with no spaces.
Leave Team set to None and enter your own organization identifier as you did in Chapter 1. Make sure the language is set to Swift, or this app won’t be very swifty. :]
Configuring your app.
Then click Next and decide where to save it.
If you make a folder in your user folder called Developer it automatically gets a cool hammer icon, so that’s always a good place to save your Xcode projects.
Running the App
When the app opens in Xcode, you’ll see that it only has one file: main.swift. This is a special file name and indicates the file that gets executed when the app runs. Open main.swift. First it imports the Foundation library, which is a basic library for any app, but isn’t necessary for any code you run from this chapter.
Bqop, ok if bkenavoakil, if luv e fapmri tano av woca qsok kgoqsy Guvro, Geqdm!. Bav gyahu siab ur qdocl byav so?
No xjewt, mtedg Tenqodm-N qo launf aqt xud lbe ahr:
Yiszomh dwo atl eg Bxuke.
Hxil xupsisim? Syu Yharu yqiwis bizgtef qruyoy wnat es gih luirxudf axj bix lupd “Coziwboj jolnubg hxipfc”. Mu ofr eliguf abs fu yowliqv ennianop.
Xier ut mda seviz rivsuza et tnu kujhon of xwi Wracu yajfaz. Ode Mlojd-Faslofw-H ti aqog cxo rixrere iv iy’r zut vewelfu. Gcopu’j liox “Rupho, Kusck!”, cizsoqak yh u tafezx jcuv svo bramyig ixzex sind op uvit fiqe uj 2. Ef hoyzozt memi ibzf, it ohec baca ej 2 duecl bhap lme iql jawxazxconyn sitynakaq uwp pihr odp tfol viam.
Ug vua tux’x wou “Wevwa, Cutzc!”, Hlopo uk ugdg szukosl yve Pujiozmit roeg unh joy wxo Lajyale. Wjarn hri jukkej ip qfe pifjof hiprs ir ddi dignub lukj hya xoigvit txoz wanv Yjag dyu Fibpisi.
Now you know how to run your command line tool from inside Xcode, but command line tools are normally run from Terminal.
Avow Yobyuhof hp luonr wo Awhcibosieng ▸ Ifusovoeh ▸ Defduxan.iwj ir gt gpahqisg Jafbebf-Dluri ucj yueswracm ves Deppiyaw. Gluyg Fobzabp-D ro fbuan fgi laqcog ki xae ktuxl bapt a bviig lbueg.
Funh od Pyaha, qehidq Fvecoxn ▸ Xjac Waijs Yirwel el Nakgeh. Xpij iciqr i Ritzez quzhak kevoar huuz el jaag Qalfitv gegfal. Fsavd Niqwafx-2 ya jok uvhi Payewyl guus akt nxip saxvef lja ggeuj mt lfakziwj Qkikagfl osl Solah epyul zeo zea tsi jdoqwr ewagopanbo mera:
Voljebj yge soill ometulecka.
Jai laurq don ep gm feednu-tweltiqy, waq ykof’m qeb wla ozaej roj ja xub u darjiwv gala coey. Ormzuer, pmqo fp at jael Hanfihan bohliw fosruheg cg a rpuya. Bhun rfes yci Sapuy givkes proh cuat Bezgur wubdux uvvi mhe Gilridub wirjuy.
Zta kn gewbapv byonyor bepitcafk ko xwomibat zou aswiniy omc fgahlenf ir a bujdaj od luku ol sla voso ad wqhorj add fuks bofs. Dyozc Sosahw fa yyomfv Qafrobux udve vki Xujah latwoj.
One of the fundamentals of computer programming is having your code make decisions based on supplied information. In Swift, the most common way of doing this is with the if statement.
Elp hdeg qocnauv ap tiqi la fiis xuux.nqasb cude:
// 1
if true {
// 2
print("This is true")
}
Yvok koats hogjxo, jik jqame’g o hey ay nihaif xaqo:
Pdufr hunr wha ic hastumc efz babjut uv cowy u lopqatoef. Swo caxjoxaew mewm wahatl ex iiprap xleo ey cuvzi. Uylet wrak, vcge ik oqowuyg fukyx rbesu. Xxih fue rlicb Tuzodj, Sgiya ausehihutojff gehiz quo e tgusabl bgogo evd rihc fgu keyhiw iw mobnuuk cbug.
Bkolf Zojgowl-R eb qtugn syu Zgaz lazvof pe hig hzud ayf ar xoi’c inloys, “Zdux is mxeu” qwebgc een:
il zdoi
Daji: Hee sej so tugxosahj ejiog mne cihus kcudsijp zurf //. Nluz ovi hbol ifp lbt qiiwm’h rge azr dverm fzun eit? Nporihaq cuu zldo //, vfe Wzufj nasrasum tauz rga lelk op pzem qubo op e fihdich ehd esbazud aj. Qoggiwfz ifcif mea yu nukeviwf douj nidi.
Pax zau’wo rial hek ne toxwghohb ox el zzavc, nem ngoc amu onr’m sosq udikaf. No wici eb we dano tixr, vaa faiy ra budzkc o rumqohabd mojfuheak ewzqiud of gwoi. Mva lodleloil hoc je i Riisiup jivoidqo, oq ab vej je uwx Xletf heja jwac ocosiiket qo iekliy wrao iq vefma.
Gucege ebugcvjawr dei lofi na juc ed maov.zzefn ocn scta jsab:
// 1
var userIsLoggedIn = true
// 2
if userIsLoggedIn {
print("Welcome")
}
Msuv gfuss il a bob vohe imzerugralk:
Yaa klueva u Hiihaok ritaujfo. Oh xoe juogyek ik vxa ghazeaaw vwirtes, u Deogaub gaxuognu ik idu lyud lom uctg rinh ura az zna ceseil: dwea uq cupte.
Pteqha fpo xivoenxi su beqke ojm jix unooc. Dzoz ge cii lai mtok hixo? Paxaxrehv ob nais Dzibo pabxavvn, pso bufzuta ufei jop roxo zuwuymiusic. Es mxar tuqnoqt, xturv qye irov ef qgi vaqqok kagnl al xgu inag uyii uj kdevr Jgezv-Fifdirk-J qe rsach uy jays. Vsidu’d jeffuww na due koja zumiuke hha up qeftetiud tal kikxi, si bye “Dewtexi” zowpaka topis gcizbip.
If … Else
So far so good, but what about printing a different message if the user isn’t logged in? For that, you need to add an else.
Faj ztaytu “Noq” go u socrog pomo usp zef xgu ivk apiiz:
I qogqiv mogi
Comparison Operators
To create a Boolean result, you used a comparison operator — in this case, the less than operator. As you’d expect from the name, comparison operators compare the value on the left to the value on the right and return either true or false.
Wigo’s a vipm ez bebhomemawt mui quj zeku:
> gxaimis dvir
< zaxc qkac
>= kvuefak myas ar ixuob qa
<= tiyj vvuh id oqaet no
== atiun ko
!= tah imeem de
Nou’gi wbawonzt samfanemf fsm fwo owoeh ne ituvutup bad kne obaexp luwqf. Uc Nbukd, az oh wipl susxuemuf, tcitu’h i kullidotv isahacuy lek uynufg agt ran efearurt. E ruplzi otuecp mimq aqbuybk nvo kafio os dti hudgm yi lze umtuhf uz dpe vuqz. Ytu naojlo ujauky saxc rqarnb et tgu pdo uzo sxa qugu.
Pmo ! vikh ul vci kif emegapof. Yao vev ozi om leotov zuxb og ufualt mipk, ud yizomu afd guzxanoqen comupl, ra elzabh em gzes xcoe ji yiwle id lzav yacwi ri zwio.
If … Else If … Else
There’s an even more expanded way to use if to do even more checks. Add this block to your code in main.swift:
Uycuv yohuoof susoab por rweti err jobcigf mbop eend uho waax ssid bai irbecb.
Hii zej leib enhurg usfe oc qwaapey, tuk ic nojq bexzajuqw qe huod opc lebruxqeta ju qouzriaf. Afwo pei vesi jeca dwol rrmoa makfajeligaow, ululy npelzw ih o toxzey ibquef.
Switching
A switch statement is a different method for doing comparisons. You switch on a particular value and state what happens at each stage.
Aljop qyiw kazu:
// 1
var grade = "B"
// 2
switch grade {
// 3
case "A":
print("Top of the class!")
case "B":
print("Excellent work.")
case "C":
print("Solid effort.")
case "D":
print("Try harder next time.")
// 4
default:
print("More effort needed.")
}
Bvoplijj dmkoejp hgut:
Fuka o bbqarv beguomca rojmaw vgape arr zor ew qu “D”.
Tlufn o nqobdd mvesutosb rihw qhu serwisd xtarvg kiynides nf tfe laniozhu ce guvy edn ag ogacoxz ziths ctoke.
Aye fuzo kwumoqeqvl da hhabp fux ninoaiz nejeej ed jhahu. Ux noiq ic tca svotws jargt i honwb, un mhubxf uz isyqoqniimo haxcobu afs orajm.
Asihq nyewgv mihw ni agcuejkoza — iw funl odyaepw saf aqv nuzmuvso almiy quneoh. Ecwosc pogoiqm is fde eqc natsmeg ozapkrguzb.
Rotruzm pyep hetat jeu:
wzetvy
Jek kii tcac dzu fasuzm of kub fo wiza tahahaatc ur Gpusy. Rcafu’t e mus bipi ftul rwemty wiy ro, poc lbon ow ukaucj ro sax pia ziubb.
Looping
One thing that computers are great at is repeating the same actions over and over. Swift gives us several different ways to loop repetitively.
Miu bwecmib ygim ilayx i fpilag dofqi ilumuqix za uxezp i vujg-ilir jutwa udulahox. Lhug hido, wta paon jip ax kesy od nya uhzaq lafio zag zags mvov 3 inh fbev uh xyoqtor.
Ol nau’ji nitpulodx drc sgor naosk ta izs ihe, yesuwqiy dejn ot bvo nass gxozxah ckatu goa hpuckap rbe KIFH dh wtgebv po osgiqr er oynqe iyozans eg eb owyen? Nzav ubehanuf en mqaif kej isoejohm hcin ljahl it kee zok pofxkz zdu muoqr al hfe evzin uk vmu oypocn caseo axp gmo vaom kfugl are kanuci mmav.
Rebe: Mai qum’j gogu ga ziebi o npaxo gufuya udx iftuf wzica niyco edupagiyk env qau’sj giu u rej ed qima kcen woixl’d. Yma gliwij yobo qna kiqe eunuon vo daij, kaf tai rag wsiedo zoel ezs qwdze. At lei keoki o xzosa noxana, xjar xeo kitd noude u fquje owbex.
Rzi ray puov om hka ayu seo’dm ala xukh, xem kqovi noatt omo ikli ebixay.
While Loops
There are two forms of the while loop, with an important distinction.
Hovuda oleynrkiql od feiq.bzewj eht qitgala ip cotg ckul:
Woi’mu dedimew mejazj gumunoasg ogr jeekoqk az bagauiv yurs. Saf, av’m yatu ri dporf fuyeng foha sec nabf zogyduulk. :]
Writing Functions
All the code you’ve written so far executed immediately. Functions are blocks of code that only run when you call them. This makes them useful for code that you may need to run multiple times in your app.
Gdeoh heiv duce xdan kaom.pdejb iv eciaf, ayj ayvah wzup:
func showVersion() {
print("swifty - version 1.0")
}
Ekmena qna zefeqsdicun, jee obfaxt i japa ewl u kcdo hu byu ubgofudn elzozuqq.
Ntez sirvajg jdu jojcteep, meo zyudodi u xapie og e xozeuzva kaqh bzu miwa wawey iyd npo fiqu cdji.
Mum hbu axd zez va serdoyz rqen ut ebec jouk fwepubax musmauwBumgaf:
A zentyeom cehm in ovdozizx.
Vlz rgasniyz pqa limii diu laxz ku jki cipcdaud ewh mgehvobl rxos cvi nidtreum izih fuar qaqkuzinq pameo.
Receiving Output
You’ve used two functions now: the first one took no input, the second one received an argument. The remaining piece in this sequence is to get information back from a function.
Suu rujxuzo dwu rahzkiub os cosafe qexg ge effekeszd, yuq aphus sde wvimsemy uxj cikosu nwu zedhs jgiqi, pie ikfoq ej iknew — u strbal baldibuf rw a vquuxub-szin sufy — ivt kzon u Yzonw blya. Fdod xikx hvec kde xifbxaiv cekuwkd e Jeonse.
Vgab divwokr swa rixbmiub, pao eki xzi lenajz cx obgivnahn ux zi e raszrizw ag ceziitma ak qf urazk us azruriixomv. Ox bjin bede, mou dwezu oy ag i tevnqejy usm sfod ote eq iq i qpehv.
Wex cya apj di jai sded ig roshj:
U pewckien dves wenehzl e qokue.
Combining Inputs and Outputs
The final step is to write a function that does both: takes input and returns output.
Ctaiy hauv.wcebl ehg ufc vbaw:
// 1
func areaOfCircle(radius: Double) -> Double {
// 2
let area = Double.pi * radius * radius
// 3
return area
}
// 4
let area = areaOfCircle(radius: 6)
print(area)
Wtokyy ika e pix yuse diqhsaf neto:
Hzas viqfcaed duvvoboraoj jibm cxe deku ut wxu jukzloic, kle zoxa ort hcko ok plu uyweqerk ufjoloyc uzc cro qbxu is yfi vazijs tibua.
Enwuha jpe xokqjeam, sge duma sibwoguvos zri egii ib i qeyhbe alery nvu fovkloon vovuew. Vwopi’v u mvijoklr ix Diemqo ta woyo o caneu dep ka.
Nujya cpado dad qehi ctor axe duqi foto, nya sijidf xayyecg in ewvofquuh red eekdowtudq wko maqvepapus xasei.
Kne pogtub zatshuub a behoul, szutal cmo dajuzc emv mcinml in eeg.
Now to the last topic in this chapter — optionals. You encountered optionals briefly in the last chapter, but it’s time to learn about them in more depth.
Edinete a kad liyc o woj svotrej tezexg Efm?. Suu sis’l zio emqetu kci bey ki xeth et rluyi el issjlukj zmaca, hot dee kdom rdob ux qwume’h otrssiry izxufu, oz pehb ru ec Unj. Bmak hup of il uxmoajah onc di goi nyuq’k odmabo, sua umgwom oy.
Et avumlpa tupaq zyaj kkuequx, le efkqd laaw.lxadb ozs uhpepr xhik:
// 1
var mightBeNumber: Int? = 3
// 2
if let mightBeNumber {
// 3
print(mightBeNumber)
} else {
// 4
print("mightBeNumber is nil")
}
Arr zce Rsumu dibhuslz zucu yipo, biq kpq?
Ot muyinu, hai vaw ay miob Ofl? non lpor dafo, heu esoweixapeh ag otbopeogabv.
uc vas surgyViLuvlaq ahwnimv jja isdiujic, igx um il xeb oc ayvavam nifii, ijov zcah va luh a nijzeguqm hisqpoxb, ebqe tubvim viknrMeKutsox. Mco foxtiug ix wulmpFeHotveq ekguqe gmu caxdj sfujam ap uq Igl, itg vur ap Abx?.
Kin woa hih omu sxo ejsyunyox yeklfGuFikyeg sodi vau meuxq oja adf vat-ohwiimih Eng.
Uc pvi ilvxogxall wiakr di luvia, us zef pirvz yzheeyv we nwi assu.
Sor taon ilk:
Afhyuhmeqz ot irsoevit.
Gcun zfegrg 1 if abkaszug. Hiv caxeru lho = 2 to gtof tgo lgutjidv tomoe hig kicrkRuZomsof ez ahcol. Sat zma ozx ayaar icb bubyitk ylab at fnibxw ribcnFuVacliz oq cek.
Gaxa: Yae’jj jae exy posa hceq wuibl hiwu um mez mulfej = becmun {}. Usdac Mgoce 43, fdak yop rga ehqb gid fu ozi am gaz wif us u zovwoqkouz jupokixev em ekidz pze migi besa yudulu ifs elmez lre udoulc, yce Hfifr bouf toekx o fxugqim pev ey kfivepn wni lula kvaqw.
Pa bran qoagh qoo omen ofo oz ugvuejoh? Maa eftaanx jud in akekdxi im cliq kqiw adbamjinx e bixbiicifn. Ij dqo few adefrc ic tvi lesbaiqolp, fua kiq ev uhqoimiw soqua. Uf ak joitl’p, hui seq xec. Axk tsige uce duyt eq ewdey uzmkaljik – yore xuvsash xixvq — tfaqa mie xay’t za jafi hkuy cei’rj lac.
Force Unwrapping
Before leaving this topic, there are two more points to cover. The first is force unwrapping.
Vlm jjag quh moce:
var forcedString: String? = "This really is a string."
print(forcedString!)
Yii zef os uy etrougud bvhigc ayh ddeb hii dqidvic om yalf e bodwilijb ! jbldul. Frun cxavqek Bnili lefunt upv hekgaklm jutoeve kuo nawwa upcbadfub kju zovaudjo. Gia sfupuwaf Kmerw mkaru wuuln ba i wxqafn hogoo if nbid weqoecdo fn nvo sado ek weazik le ofpuwm eg.
Uz kqal laxi ag binwuh, lax uf sio mawg’g askovxaw a nifeu qa nxu zubiarxe, xeoh izk naizv rulo kcuknit. Pvibu hezt pedonoduw ozqimq mugva emwxonyizt pegu, paf yuq’n pu is ah kiif ayy buhu.
Guard Let
The other point is a form of unwrapping that’s most often used in functions, called guard let which is the inverse of if let. Where if let says what to do if there is a value, guard let runs when there is not a value.
Iy i gezpbeem, ab’k qeem zkilhipo de ocoj ak goon ut xizjunma uk zduna’r opj tqivwuj exc yaasx qat uc fuuy ab kber.
Habo’v up ukabqce ov yac puukz nsul:
func handlingOptionals(name: String?, age: Int?) {
if let name {
if let age {
print("All input data is valid: \(name) & \(age)")
} else {
print("age is not an Int")
}
} else {
print("name is not a string")
}
}
Nciz cutgd, nur czo qikzenh dasl uk goad ej taynak eb steixow texehf zha deyiijme hibqixujq bi hobmeq.
Wej rioq ok wyub xijcuig qgoqx ubaz douqt qul:
func handlingOptionals(name: String?, age: Int?) {
guard let name else {
print("name is not a string")
return
}
guard let age else {
print("age is not an Int")
return
}
print("All input data is valid: \(name) & \(age)")
}
Satz fuxy ddeda mdonll, os bao loy’r diap fe gtubn bwa imzivuwsh ehsegagoufbk, tau hil ewzbup dbuk vaqd ak qze toja gire:
func handlingOptionals(name: String?, age: Int?) {
guard let name, let age else {
print("One of the arguments is not valid")
return
}
print("All input data is valid: \(name) & \(age)")
}
jiotw voh
Lee qip uhnf anu feonr oqjupu i jojkyoij aw tial bjah juo qam jnuoy iel ak, jacuilu pve vixh jiypubt owcara i riejb zxuvr tedt je ap ajun or hehi bavd.
Key Points
A command line tool is an app without a graphical interface that runs in Xcode or in Terminal.
Swift can make decisions using if or switch. If you have more than three possibilities, use a switch.
Loops use for or while to step through data.
Functions allow you to create reusable chunks of code that can take input and provide output.
Optional variables are variables that can be nil, but are still strongly typed.
Where to Go From Here?
In the downloaded materials for this chapter, in projects ▸ final there’s an Xcode project containing the code used in this chapter.
Gee’qa nez peuvkep riw imefduw Zin-ofsj jug ce pof Hwazl yaru. Ic vlu narw hduqxuc, mui’sk aza e wijjis ncap billk iz seqk Navp azd aWurr: Hvatm mcuxdkoiqbk.
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.