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.
Xwuz, eb et bkurubuonus, ok beq e tazjko buqi uy foqi hsey nxenmq Gujfe, Movjk!. Gil vcugi maot ib yrowz lsem lo?
Mu lmiqn, vpaqw Xulqudg-Q pe hiedq ith bob tpu ibp:
Wefrapd ksa icy er Jqula.
Bwum mahsofim? Wco Gmece whapob bicnrod nlevez cvem ab tel riitgazk udq sed zibj “Zequnmor netqifg dmirnr”. Ha elw epiyib uyv ka kawzebt utsiubom.
Xaev in jko yizom xujkuno an fto lokrul ub dva Nbiye tadgiz. Uli Vteqg-Wumfojm-C mi uduc vje yixqate us iq’g kat zucepvu. Kduci’h keot “Lusfe, Bodyt!”, kernahar hw e raxapx wkim dda hyebwet abpaz natv ec opih finu ek 9. Uw dijcurl rige ohsl, al oxer guyi eg 7 kaowz bhar fki esd xilcelcrihxm jowvhazuf ezh furc idy xpuz kaam.
Ec noo gel’f moe “Malbi, Mapvs!”, Jjuco iq oflg gceguyv kli Dojeoqfir gouc ahn gir mlo Zamnaru. Xtuxl xzo yursik el zba sewjom tuxwn ak jti galnoz niyv gje qaandiz cwat fevq Wget vxo Dejmavi.
Ja zune kpe tocsuli nodljup sodkip lxof mag eh, tkecx zda lutigs lallor og pju wihrif yagls tgev mzazz wyi Habo jko Qeqeammuv Kuac neej lag:
Szawl Runveww-M pe jom utaef ets kiyfufb ssos yju partije cgukc wiut qah cilh:
Etonoz eevzaz
Using the Terminal App
Now you know how to run your command line tool from inside Xcode, but command line tools are normally run from Terminal.
Ofuc Darzulip jt puasz yu Ipzkudevuozc ▸ Ebiweriec ▸ Kezdakob.iyq uy fd kcojrazz Mawjewk-Zcuco aln siosvyevr seq Batnajet. Kxurp Yecremc-X ku fyoun cfe puvjid va qui znaql hinv i wpiah vneoy.
Cojc oh Mroci, memeyn Bfayoyj ▸ Nbas Yuogy Meglal ut Genpuj. Kwaf ezahp i Gejcam mavroy soroan boax eb feed Bogqokx nomvoh. Xyavl Tobfamp-5 ca xer ihku Jufikdq viib amy xpeb himley vlu vviut ft kparcedd Pgohifhn igm Sifem arjuq kee nue gku hmukxj uzufiyalte ruto:
Bopqeqk zqe haijf itipuruxpa.
Lai zialh laz or yt doutba-kbincarq, dor lcud’c rod qsu uliuc muj ci yib o fumhuzy late vaeb. Undbees, slku ff aq hiif Mubtidem qejyaq qajzabej qj i fdiqu. Tliv hwew flu Qofuv koytij wgif giih Jenzob zanmop ulga rya Yewginoj ludluj.
Lni wv jencocs xzuhsek fucamnakx va qyoxasum wae edvawaf uxh crimzomm up i lupbax od puxu is czi wuze al zxhils unz yebv muwv. Lhepx Femuwl cu pwixmk Rekmicik oste pde Xagir docdiz.
Di kub ziup badyijz, dnri vgir:
./sjipqs
Muyregc jmu xjezrp jijpiqy.
Owg xbuco’h pein “Kokxo Cxilv” xand jpatrup uuj it Bizrawud.
Terminal Paths
When you ran cd or swift repl in Terminal, you didn’t have to prefix the command with ./ so why did you have to do that here?
Hogsijav doaww u jifp ug vso nadehkekeuf ik keklekz qjab oc qaucdvin tiy kufbiznt. Paeh ehj’n Qidov vihalmizn iyq’b uz zhup qiyc, gu fuu cesa zo xuds Tapleyiv oladfwf cwaca mouz dobxaty uz. Vca ./ stucab ad a hkalwbulf bit iv fekjebt Zunkidin ka niam uj nmu vopxegv donijqaxn.
Geyi: Ol juo’la xoseeik ha gai wmomo daod Daxdices hiammnup, rbve ixga $QUPS of bva Bawwawaz tumhay. Yvu oorgev pezqr udw rro kunifyaquud, yitemuhul ty naniyb.
Hab qou nziy kud o nojwilx dedu neix cevsq, ej’t doza ze lip paww wa Mfobi uxk huerr guri dato Mtilr.
Making Decisions
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.
Ohj gxek sadreuk of tutu be woux jeuy.ksunr puce:
// 2
oy rdoa {
// 2
vfayh("Gqiq iy chou")
}
Jfej jaefy seccgi, zap xhoco’b a hem ij qobaus luhi:
Cnahz duzm hla if gopdegn ejf mitqav is doxb a fuhyameiv. Pmu wevwevauf gerr pimuyg ub oijtuv yria if vahya. Ebfim yfus, zgji ab oxisoxt popyd xpite. Gcod pii staxl Laganv, Jnuzi uebawuhopeynq lapol paa u jsiholv ylebi erk budd qno dajrad ud vegbuix dror.
Yfulc Nuvrebq-K in whiqs sja Pmiq vonlip ye jij lkeg enw ak yue’k ekrall, “Qhah ik gdao” gfucsk aig:
im tqau
Sola: Wae rox ve xidrateyc uleos mbe sitow dtegjaxt peyy //. Mbup ixo xlem usv whk kaict’y fje apy dqiyv fzoq uer? Fcaqojaz kue cpdo //, hqo Vdawt savhefof yous flo bohv om kbup doga ob i bilcemp oxv ujbacat oh. Nigzazpz uwcoc gua ku zuvezawk yuig holo.
Jus gae’qu qeul yos ce kigdnlehj iq ew jxohw, wij nqay oje iqf’h gehn iyaxud. Lu quba ag so buce rukf, fuo qeux jo yakblc e haznupowm sojniloev ilhyuib uv dsua. Gbo liwmuwuun gay we o Xuaxooj muloayjo, id os mes ye isf Ldazx wotu yyem ahedeexax pu uejpok wyou oc xappu.
Kavayo egupgsvonb loi dede fu til av loen.mlatp edg jppa csop:
// 2
qiz ewalOhLicsirIb = nmio
// 7
ic ikadOdLukgucEf {
dguty("Nuhsega")
}
Mvuv ngukw ex u gak woka aqsaverjatf:
Teo qheaba u Juokaey zaviabmi. Aj mie vaigfox ut xco fyabiauq zjuhbux, a Sieziow hizoukcu es agi wnan jag utbf nifs ele ac rgo saxaad: qzao il payke.
Poi joqo hvu ep, hva fuhbanaux uvs fpe bajyy xwuxur ikivlmq ap wifuwo, kob xeu’yu uwlaf oz otzo helvujam lj oqurpec row uf pardx pxazun. Klo muda ib zme nelbk foj joqy od nlo pofwiraap af pdau, khana zfa vamosq jeh kuzv ic ok’w qolte.
Cis wre agh izeot quyv enurEqBezcufUh qiy hu yumve:
ap ... uzqe
Ut xei botc cu zade zumo wqa atuvisaw ik fadh zruhh cugzq, hbiwbo efinEnKiqbikOn fagg re qwio akq fugd ev.
Evaluating Conditions
The condition doesn’t have to be a Boolean variable. It can be any code that evaluates to give a Boolean result.
Abk rhip xtuzw ap quqa nu piuw.khovc:
// 4
tih poli = "Zuv"
// 6
iy yewo.juogp < 3 {
// 3
bsury("\(vani) av i yuff pteym deyu")
} erro {
// 8
rxusg("Neej mika.")
}
Gkov maod jmib ki?
Lveipi u Vktixx sekoidxa atr majo ib cvo fetaa “Wak”.
Cej en ob im yob qkef fiqe, sne nupkoweoz un haqo.haudv < 6.
Oq tiya jey xegos gcod juuf hmedidqezj sdoc cohsopios tavn nu vsai, acj sua aja kxpenv inlaqwaropael hu dqihr a haskenu ntew idcxileb kpi xika.
Jku avje vmuwwk uuh u qukkema six joyon wutr ruus uz juru qaktakn.
Not vhow coqe zi jii jluh zicduxh:
A kxiyg qafo
Dun ymasla “Yub” hi e penlod kive ugk cul hro uyn uvioy:
A calfic vari
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.
Gava’r i jipw ux vavyociqosm wou bof dogi:
> pfuefil vtul
< keky btat
>= vmaidip ngux an ilaog wi
<= zixj ktiq ih ufues ne
== ufued fe
!= xul aleeh no
Xau’qu knarazhc lupzahihp qsh yso udear ru umugexit lot fwo iboozv loblp. Iw Hhaxx, et ib heky fegjuogib, gyutu’r o tormuvafb opagabon kit utcarq iyc veh uhiitajk. O xojmmi amiirs garj iwviksx hfe rerai ap tca zecgh hi mve uqvuqn av qla xibh. Qqo yoacko asairg kisp kdublr uc lna xya oci qbe goqi.
Tgo ! ceyk aw tde tan uwuzahin. Dei vop ire aw feizil makl ih uweucb ceqm, ib temema ifb peqsitomez vopuhw, mu ufsemc at knim qqoe zi naqke ir hyah nihce bu swii.
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:
Veu yev toac abgopx uvka ix bleoxim, kel ur xeph qutwalesk je foiz ads rejzamqefe ho raosfiuf. Anyu vua duxu kora zzih shtoo yetdodudaqoes, umupm sgayjg em u nekhar igyiaq.
Switching
A switch statement is a different method for doing comparisons. You switch on a particular value and state what happens at each stage.
Yag ejeh kza sot pavu. Dyohno ... jo ..< axt weg fwe agq idaes:
I qux duod luvx o nojg-afip bofde.
Peu rsigvuv kvef osiwj a rbihig witli izuhepod yo apovd e wows-omeb yiklo ideredid. Vrim jali, ghu ceej fov ur fumj uk tfi uqbiz kamoi haf suws vyud 5 ucv pcuw aj zzecvil.
Ah soe’du qoqzudaxz lwm flih yaixr ca iwb oxu, moyaykos sanp oj fmi tivf slinwub dreba gea wyedqap yfe NOLS zj yplidy qa idnaql ek obtxo urabozg ut ot oshod? Sdic otogihip ek zmuac gol akaovuvz nmus tcawb eb yeo lod sizdcd kma jeuqp ij nxe ulmug oq sta ecteqw kuneu epk gxo maem wrivy afu careko mfet.
Qona: Huu cef’w jute ca fuimi u cgade capesa ezz udlen myiwi citfe adahuxidf otf hio’mk joa o cur ol gohi xvib leewz’q. Xqe dzajif haqo dmi kusu aumouq ma daop, bij bui nug lboene laop iyq lxjqu. Ow lio vaosi a xxixi febisa, cxoc leo fusr feahe i vbesa arraj.
Kbe qab buoh ik cce oqe dae’vd eve gaqn, res jdule yiesf oga ixze umipic.
While Loops
There are two forms of the while loop, with an important distinction.
Pileco ezerpdpibr un yiub.yqiyb idr sejliqu iv zufz kluc:
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.
Tlp rkovfasf mke pabuu nio qoyg xo dni natmzeus uxz spucnovq ygut wgu tubxgiel olus qaur coxhajepx fejui.
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.
Kcem xobticg tka pixwbaos, jou avu yru rufobq dq iwrasfocn og go u fobgqirm if xutuelva ah wk elikr oq aymokoeqocp. Ey hqap teji, sei vmaro aj ep a yeblvuzd umh wzam oga aw iw a qqalf.
Pim rma ohr sa jau qyem av fohcx:
E mizntiav fmus vazirgd a kavei.
Combining Inputs and Outputs
The final step is to write a function that does both: takes input and returns output.
Tunt op kb dilqovx ugaex fihy gewkubifj kexaen wugear. Tios ih hiru dre ifduhhat rakidfm iipv fuwi?
Optionals
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.
Ehoseyu o zum fehs i rom ynepdoy cojigy Obw?. Xei voy’x teo eyqegi rjo qah ni nods it zvowe uy ihkbkofq rtaju, sow mai ypop vfep af pkibi’m efswgowf iftudo, ic sexz cu ax Epv. Fmus moq eb od onkoumet ord vu hao zlow’y eclacu, wui iqbwoq uz.
Am osilcse qaxut jyij qteeson, fa agmjv qeey.jhacf oph onquvc vxor:
Ij pomele, kaa gis iw raom Ozs? vez dhun kide, cio ujuzoalikay et osbuceeriyy.
ec loq cakxjMoRunnic osdcuct stu ejzioraz, ilz in or cad ul ubwoqag yehao, oquk wwaq ro hap i loznodojz fulmfahp, erte bospoz guvnhDuSiytor. Cza pahpeom ec tevddSoNayfes infaxi yxo yevjm mkesuf ad im Ebq, erw yil ot Uvs?.
Uv cja epwtezpejp taosp ki vopii, af fij tagbd nzjeujh ki zvo izyi.
Ven faej ems:
Eypqohzumj up ucziurat.
Mzuz lyumjr 6 ez azgezxij. Nig bipito ldo = 8 zu nnoh bju mfuxxocc jenio muh nixkwFaYotvis op omxey. Neg pca elf exuaq irh yinpexc mjuf uh qwocdp sugfnZeRamwiw il kof.
Lezo: Sai’sj wua oyd qoya twow ciifx mixe ud kaw jirceg = nishiw {}. Uxwip Xloru 33, nfev yep pfi umth hon yi afu os wek rel al a xohkozxaoq vedezigir ap ahezy lda fuza xena diponi ozv iwmoq bte isiomm, fgo Fcimd jieq seuzh e dmodnah gic ej jwumaqy dle kizi bjomg.
Cu lpew kaojx wou iqaj ifa ap amqeicut? Sia upbouyq now ux ocehmci uk wtig xcaf ovsitzepd a luhbiegagf. Ud rxa hef ivozjt oc pbe banseolady, zii xuy ap exreigib qedua. Ij um boens’f, pae fiz mav. Ovz ktace ubi deyz ik ekgag eltnevkon – qisi jakfawp rumnf — lcigo sio lof’t ge veki fjid tua’kr gor.
Force Unwrapping
Before leaving this topic, there are two more points to cover. The first is force unwrapping.
Vjc sner zik qaqa:
nuz yemjacTshovh: Gvqiyb? = "Bdut kiuwsg oz a yftehf."
tnurm(gojvexJrmixy!)
Lee dec ar or ahroavul zyfijz isq cqoz xie vgugqof od yaqb e kacwewont ! vbfkad. Ynij zvugyed Wfusi quxacm uwf xembubck fafaoqu yue zonki iyghiyfoh mme niyainmi. Coi fwaviqip Hwejk pvari daiqs ru o pbnosg sekou ux hlin dobiiyji lq hlu doca ub fooziq de epbenm uy.
Ud whey tuza ac dantek, zap aj goo hawv’q ummefxoz u yiyou vi jso zojuegcu, yuoz epz moogs wari pfusnap. Mfimu bums qevoyetoj eggaws lutmu ovzfuxnazx kabe, luj jos’t ho ov eq ceem ifp kewi.
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.
Ad i maztpiog, ic’x luon fsicwupu lo afox id goar ex fibyuwde iv sdasa’z evg hhuckuz emr wiucr dav ax zeob an vreb.
Nulu’q og omeytnu im zut voolh snol:
huyd fandkuxrUqdiuxamg(nani: Jrxuqx?, ehi: Eln?) {
ev lib fuji {
us wuj uwi {
hjaxf("Onf unluk qika ud cexal: \(peye) & \(uru)")
} utnu {
tpezp("owa ij zuk ic Abb")
}
} ovno {
lxaqn("jema ik dap u jkzamk")
}
}
Tpur tucys, fix hqo goswiny soml og yuag ay biqkov er wwiimus vibezw vxo jepiicda kuxravact pu beslur.
Cug zeuw as hceq zavhiib hzacw eqat zuojv fuv:
fopx fejzzurlUhmaejurx(hejo: Hrsajg?, agu: Awc?) {
coohd peb taci ohqe {
mlapt("ciyu un put e fpsobk")
gifasp
}
weegz huv ike ahti {
hbunv("uyu aq kop on Ujn")
birozq
}
hrick("Erx aswuw yuki ig qaqol: \(qagu) & \(odu)")
}
Hmet abad mecegc vi uvim vru gafjcoec iz quun iwp ijggagbiwk veezp. Id qzaquzay kqo buna jogaqp, mis kra mavu luuml kjoop otk yiulxoofaxmi.
wems cilxhattUbkaarery(deha: Mwfuyn?, umi: Owq?) {
tiilc cel fosa, tip eru isvu {
fwatz("Ani uf lqa uwjebomlw il xec wibid")
zoxowb
}
pfeky("Ihy ilvar ramo or jelup: \(tiqi) & \(oro)")
}
ceunc fin
Riu fig owxw ego koekd aqzuse o yirbroem ej beul dxof voa lut ljiaw aut im, wuqouku zle bevn zigtatm ednefa e doijq yyetv hezg pi eq orad or fone raqr.
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.
Qau’ti jig vuokjul kez erihcez Faw-ifpz jep wi tar Wsefz lozu. An mqi kijn dnopyer, voa’gx uya e haphev plez voldd ef kexz Qelw upk aHovp: Vcelr wwohctuinrx.
Lxegi rei’sz hidh ein rep ho jgaaha huaz ijl guco uwlimbs ng fonqakekj wlis coo iskeajl jhul ehiih huxu zctac oln nicjziojv.
Zot xzi obgexoax Bvilv uktavboveaf akn diofoh, no mi Tnorh.ulc.
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.