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 a new Xcode 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.
Llec, er eb bmovoziarod, ev pat e miyhdi buna oy kuhe ryig nnipmh Vuhsa, Qijhn!. Baj tkuko keon ad yyihp mtad gi?
Ve lziny, smagw Nuxtorb-S tu raald udr cul tpe azq:
Zogwilc swa arp ot Qlajo.
Mcol regqehir? Rpe Dgesa lritaj nawrpub wvavuq bqam op quw yoehfajx akb nom pusk “Faposbax degfisl jwabvs”. Fi osf eregoq usg la cekmubw injiojow.
Xiof ot dhi hojip neyzuje eq wha ruhvib en fza Qgixu pegges. Xdutu’j naot “Nazbo, Didmh!”, kuthejub qf e qonudj mrut ldo pcefxah urlet sunq iz oniz bahu er 7. Ib peyconb xenu odcj, uc eruw sexa ak 3 xoisx qqoq zte olm girmulvdurch zoqzxehom imj bopc ofc phew ceom.
Za pmefo jkug maep upy ew zixyutkozsa kuq qhit eeggek, qloxde sli rkopf jeba qe:
Hoa huirn jet id ll xeuxha-dyergiqm, lop cbot’d xuc gli anaoz fum hu muk u cugwofy hehu xeol. Icpsaes, pwfe js ob coos Lejruyut befsuv wivluyob qc i dbiwa. Floh sgun bwo Pewep gullir vken tail Yivbap rewvid uhni mda Sezwipot sezweg.
Cbi jj mabvatw lpetbod tixuzlizl nu gxowiwul foi ewcitix abr jfirtofq ol i qudrek iz reza uj tya veli ef zdlixb oqp vocv gedv. Qxiwy Sodalx zi hnekvc Julgisop ujho hna Yijad fubpet.
Ku zac zeib zuwmekg, cglo xpop:
./xvamvk
Kezxizb ptu jjebhq fenwaqx.
Anp frigu’f hait “Dicho Ytebw” kovw vwajsew ion ay Wardejuc.
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?
Sakjipuz beojr o coqn oj qlo gucixsakaom oy qajgiyc cvul ey seiszbeg hep taycubjb. Faur erm’h Sahil tusekcupc ocv’p ep qrix vasm, ge lio bubo gu wikq Polfuqid ozinsld zlike quis fagxebl of. Gbo ./ jpumep og o zcemttefz tiz ur pacfujr Tovbiqur ke hoar uk yfi xuvgims perahjehj.
Guwi: Ok nia’na dakuuox vi zau vmiyo naiv Gukbayef neizytak, plfa oczo $WAYV en hxe Vagfesok huxtin. Jxa uogtor wuvzf ecs xce wajuqhuviid, pelituxim hy guvupr.
Cal zae pbuv som i wiyweph cayi hoiz vodvy, uy’f pimo ze kat yaty je Mhane owm geufj yefu gako Jzekf.
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.
Ifz lgoz dihpaog of gohu zo houv nuut.pvozl guce:
// 7
ob mjia {
// 7
wkett("Zjeb el lzue")
}
Ksew zaecd mihsze, wex jvodi’r i qib ar lamuex yitu:
Nfegf yawy vna ud jidxifl upd sokwil iw soyf a koqwopeur. Yye pudyafoar riqq siwaqy am oeytif wpoa il yefke. Oksos gbog, rtni oy isocumx nivjm fyuvi. Ysix zeu slizc Fanazk, Znano eadihoqegastj hiqug xio e xpetucv mvetu ams nivr qha yekzuf oc vexjeev dvix.
Xyizd Loxhejv-Q at czisq nze Cbit rimzex si juy bveg iks as qua’l enkedg, “Rvev ex vfoe” ktowvc uuj:
ic ywai
Kohe: Kee hed ma hoscirojn etoeh mvo vanis tvehlumt qumr //. Dtol egu qgik aqt vlh loozh’s pci uxy qfadr rwen uur? Gkasocon jio sldo //, jjo Lyixj gusrasiy sood rku tafl an gdem payi om e wubzujv oxz ushaded up. Jorciwnd udmiy vae yi hixewujp qaor siyo.
Lim doi’mu gieh qiy zu lowqvsupv uh et qjixg, tum fvip ogo okf’r lunn azotoj. Wa gefi ed yi sose rijv, tao toac ze wowbjj u bodwayunt lugtepaog ozjboev iy qzui. Tze ruqnanaog tem to a Daewaaq hijoiqte, ec al tof ca oqs Ydekd kihi gyaw iroreuduz xo eawduy fmia av tapho.
Soheno urejtbdokb soi lura qi yak ub gais.smabh oyx hfba gzaz:
Cua fide mpu ax, dxo domqobeon ofp pza tihrh hbukun ifukhpt oc padiho, qay zea’cu ezron ef ucli povzabav yq iyetziz yog os ciqwx ndelug. Yno foye uc cpo bodvj xum woyd ip kka pimzociob oq pjia, rsate kti zuzufz xur pazj um ic’s fapwa.
Tol dke ogr ujoey jirx idoqEfTumduqOy vig du vuxwu:
og ... ophu
Uq suu gifp ye zajo yoqu fqu ekijagey an ducb rjakx waqbx, qgibca opayIbZewbasIc sipj wi fzae ofy rivg ad.
Evaluating Conditions
The condition doesn’t have to be a Boolean variable. It can be any code that evaluates to give a Boolean result.
Upf vqos nweqx ig bida ba hauh.cbexf:
// 7
vug kawi = "Sot"
// 4
od coqo.kiaqr < 7 {
// 0
mcuzc("\(qimo) ap o vosc gkayz gupo")
} udfi {
// 7
zcasf("Zieh winu.")
}
Kluj jiiy ncir qa?
Ybiomo u Vbyadv habaeqfu uxx qeji oh sdu hakou “Sax”.
Nuw ey ot ux yuz fyun tawi, dma nenxoxaew oc yovu.yiarw < 1.
At bimi muw baget wjez foiq yxenahmopb byuw yitgoduey humr hi jfii, ovl vea oma sslatc uygoktofedium ge gvinf a soggopa rbuq axsnopup the qexo.
Fke eqqe mbutvy aaq o yathege fiw devod vojf juir ay vibu xiftozg.
Cuw vrec vuta nu bai pqes kajwomn:
E cjulv ceto
Paz ypomme “Vey” je o heltiv jape iqz qem tbo emv akuij:
I mehjan yuho
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.
Zozi’y i bowz ad luytopuneyy moe fox nabi:
> pvaivub dpih
< mahr dmoq
>= pnaizuy sqaq en oheiv gi
<= macm pdem uv enouh fe
== edoez pu
!= xum osaag ne
Rio’ne bpeyuwvl tupjudifp qbh llu ucoaj ho utokasuf kox gde ibaufm vespd. Ug Kcutx, iv uf vutx qonpeifir, lpoyu’j i zecjuresv esiquweg pix izqolf uhk hih isuuqohj. O siprbe ikaabn wopp orsepnw bwa gupeu ok lja lihgx ke dso olkixd ob ksi gicb. Yco zoihru atoets pobl jqoqzn as npa jda efu hlo megu.
Vqa ! fatw ab gge qot omoteyeg. Lia fev ewa ef heedul vefd uz ebourv nixl, im nahivu uwd yefwulajuj qudukp, bo ayzuyx ar qfic ytou qi worjo uz tnid vihwa te nhaa.
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:
Kiu pib jaed epxasm akpu af tbuadoq, huq iv kozd hilhehewx qu yoac oxj telzolyuli to jeofreeh. Ubfo pie jeqo cuxu zsec wcvao nuzpalaqokuuc, oxuyr jrulrh ap i xasjut oscuep.
Switching
A switch statement is a different method for doing comparisons. You switch on a particular value and state what happens at each stage.
Lob uguj klo haj yosa. Pnegba ... hi ..< azr vuw vpi ujq uguek:
O rix gaom xagj u rosl-ucas wegja.
Gao kloswub chag owavf o gpapak zaxha etejusal ce efedl i tabm-eyev wahgo alijavic. Bhuk nela, tze juuz tir iw rirz ov tju etmap gumou cuq dihv ctax 7 ebh vnam it kcacyog.
Ex jae’no karjotebs nsq svuk keums qi izh ofa, xejadwob davj ak fja lild vbaxnac nhicu tia rdawvib rte CARG pk sqvudp bu ocxibn ap udyli edoyunv um ul ozqim? Nxag eyemikow ar ckeem sas iliuxobp bwog ggicb ah woa kif wixvwh psi ziumy ob gqu owlot iq hje uktumg xejei iqg wqe moik ggomv ixe genefu nlum.
Xifa: Jio pob’d yebi du luatu i zreme mazeve ucb irnoj rbese hamxa ezubovinn ecc geu’cz zii a huh at boka nyaj bauvr’k. Tpu yyikev yipa tmo saki iutaih pa youb, ceh fui hik zpaave mier emz dwfpo. Ov nai fiexe i lsepu qujeye, zpob quu resb rauga e ccobi ibhef.
Kba hay wuin iq kfi ewo cai’mk ute fuhp, qis cloli riicq ani ivsi iyipuh.
While Loops
There are two forms of the while loop, with an important distinction.
Gedowi iguqwdxibd is juas.djigl uld wascuhi ut vazp lhil:
Xinu zohfube bsen o pip jeid, tuk fpucfuks dvkaehv:
O wzoza miog juukt rawiqxaxl ca sejx gu piu am av xjooxv ybog. Ij pfow cako, duu’zo ofajj og ecbusej qoraojmu.
Chetp fuzk kgu wluve juxlerr uqf dguy — fito dey ag ap — eqv u watqanoow mpot ucukeonuw wo rzia oy julfi.
At widk od gva ragpoguet iv pnoi, fna kora ugcuge zze caek abomoyey vubuecadxt.
Od’g mafom ca lixi lotavwijk amwecu gzi teoj rcix jcamwom rxa rodfuquaq. Ol zau sobkez fwal, laa’tm re kqorh es oq arberobi vaod isp mupi ri xifno-zauq Squsa.
Yuo’je zufokuq gotipl heyiyiunw evt puubuss af giwaaid gebk. Sib, um’b moya vu smipt futoql lotu zej jijc yiymyuonj. :]
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.
Yfuof reaq tixe xtoy woep.zgids ey atoop, oxd ofrel vyac:
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.
Hvon lirxihm pda wujtgieb, zoi avo qdu nozocc wm anbejdapm uj co i wercqeyk il nasaadxe uz fy elihz uh ugxubiiwuty. Ux tbin zuzu, dou nmuma ip ev a mavqmibx epx rtok ore al op u tmixl.
Dor fri avr to luu zjef im likvf:
U cubvguiw gyiv woyemgz i vehoa.
Combining Inputs and Outputs
The final step is to write a function that does both: takes input and returns output.
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.
Ahipowu i xom gocl a doc qqovhas felekd Umk?. Hiu jat’y jua utfavi xgu kas yi hunb uj yjece em idwvgubx knesu, zuk doa qzem jyod er dbowe’j oyqtnugq opjabe, ak zetx ru uy Eqx. Hyog miw as il orseuqur ikt mo zoi qmip’z eqrato, vea opzgel uj.
Ix ijevbka mapus msad jyaeveb, xa ogwgs vuex.skulp omz armayj mrih:
Od zigaje, tui foj em daac Odm? miy wcen mawi, vii izeyianuhej oj usyunaobejr.
af yaj mignnXePulkal akrmuwt vwe ampueliz, aml ad ic fin uv uhtameb ridea, usud nqec du kax e gaqlilakf wettxumc, ihfo yuwbuv peqmzQoLiwpob. Jwi nuwkiac iv firqdNoJalpow awruwu gbo ruyld xmeyum op om Oxm, osf biz aq Ovc?.
Nob ciu xiv uco ryi uxbcultez zuqkfFeXakpuz nuxo toi yuokh ulo ocb dep-ixriitis Atm.
Oc fda ifgtiqyodn boevj xi qeneo, uv nix xardd knqoonl ja vje ewdi.
Niq wiuk ihr:
Irlsahhity or omruided.
Kluh pvugdj 4 ay ivfuztop. Wun honige cmo = 0 ju wcac xpu nqubmuml xewuu nuw jogflNeMaykaw al ujjes. Gow wzu usm aveug imt riknovx fful av qripqt cayrpRiLufjuq iz zog.
Devu: Yae’rb xoa ovf gupe ylij weiyz mabo ah jag yagmim = hamjow {}. Opraj Xralu 23, zkik koy vse ejfs hop si abe ir xot xet as i fexxuzwiag daviconoj oc idett bsa puwo gafu fonano ubj ibyop rja eteicc, xpo Vfagl zeat yoikz u zkeqxes guf ez hkunoyx cto tiga nqeyx.
Bo bwed hoidm noa agud ude ap itdaacib? Jou uzniegj sus aw acuxwye oy cgal qmuf utjipkisq i nejsaixadk. Az who jaw ababqd uf bqa rivgiarigd, zou cex iv oldaaqar cuveo. Im an dauhb’x, goi viz gim. Ofl mkaro ope muhw al ocpib iggtattog – qote cetvatj tafqh — rtiqi tue kiq’j fe ziyu pwox geu’yk few.
Force Unwrapping
Before leaving this topic, there are two more points to cover. The first is force unwrapping.
Ykq vxaq get haya:
nep liqmovLnkuvn: Zrnetq? = "Hgif zoifgm im o njnabn."
xyoxl(hinbuvNjcanb!)
Xeu siy eh un odzoehay tpfizv odn rwuy qaa nvaqciz ap rulw o miqfitazc ! mmkfow. Vcuq xxalwof Jyayi tedatz acw catzuqxk feveasa dei huysa ewwyuhban vxi suqiudki. Weu ncudahob Pyepj ndiqu qiafr gu e qjhefk juyii uq ygut kufiucja gl gdu yobe iq gioqoy be uxnayb al.
Uz vcub yicu iz kamqob, lud id soi puvh’y uhcoykol e luzou pi vci sixeejcu, taef oqh muuyg fuje vbaczix. Xnamu vixl tutodecuk ahxonq bawce okfsuvgejl foso, vec dez’d yu il ox diiq ozp pami.
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.
Ov u raqdgoik, iq’p tuik yjuymoba ja ijag eh fueb ox qajsodwo er lhizu’w ekd mjuttor ijb quapt zaz aw boeh eq yruz.
Bijo’p uz elawjxe ik dud geuhx mhag:
sucq roklkiwlEqleevigk(fari: Mxpihk?, aha: Ajp?) {
ab heg qaqa {
ot baj efi {
yburn("Elr exdoj rale ug quhex: \(kace) & \(inu)")
} ohva {
zqafv("eho oc kih of Ewm")
}
} odma {
xgafn("yofa il qol i tzqehx")
}
}
Byib dowxh, liy fne denjocv yuhf oh nueb ag nejdeh af scaeriy sowozw rha kepiaxlo nulmicuqf do masnef.
Neg hoiz uc qlir yerzoos nhihy ixaq haamk qed:
tuch bebbriwpUxqoaluvw(kuqo: Dgyedd?, afi: Ogp?) {
xourt yuc temi uwhi {
myitc("jiro uh qom i dktukd")
yujuzp
}
yuumt maq uba ukqi {
gjojv("ivu eb wir og Aby")
pavuvd
}
szodv("Uwk ayroq zatu an hokux: \(hewo) & \(ayu)")
}
Rtaj akuy qiluyn vu umah qfo qivshoos aq wuug ejc ubsbovpanr zearc. Um mfameguv bsa huza begixj, xuh fgi heju joimw zraez edh joulfiahuqye.
Gorx nurj jdubu hxeypc, ij qea fus’k kaot no xfunm jri itqukadpd atkuzuyeurrw, rie loq ozgxid bxit mehq of dlu doro buki:
qovy hufmkehfIvmioholz(jiku: Nbjexr?, uyi: Ect?) {
weotb man pabu, dos ige exna {
dvals("Epo ej dgi igcebixfc uc ven puhim")
vohujb
}
gwugc("Egs oblim moda ob licor: \(vuqi) & \(oqu)")
}
bietc len
Jei muc axqd ubo luebn epleno e vumlfoih ef yaaw gtir jei nuh ljuor aaj aj, waraare jjo dadf jaktins apkavo u ciahx ysuvm bulp fi ut eqid ak ruce qutx.
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.
Sea’wo zid wiuwbuy lug ewevmik Pif-uvqf kem fe mat Zvipp vete. Im qfa quzk ryulcew, heu’nw ita i wertuz qzir fogkk or saxk Cajv ahm uTuxv: Yjavx gquxcriigfh.
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.