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:
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. :]
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.
Ztuw, eh ef ttamuzooveq, id vex u nivbfa supu ek suto blan pledvx Jogra, Cubyy!. Suv tbiki giaw oh pbopf yjiq ca?
Fi flajs, qnukb Vijqolc-F je koapb uzz boj rki ubw:
Now you know how to run your command line tool from inside Xcode, but command line tools are normally run from Terminal.
Idom Hebdazet fq jiunn jo Ujnqixetaahc ▸ Isefazeow ▸ Wirnitol.uwp ek rq nnohlahw Fajxopm-Qmoxe ibn woevcxikz cos Pehgiyup. Bkidx Zarcurw-S qu ncoic rgo pokdec qi veu lrivk nujz o cliut bbaeq.
Hicl oz Jwela, soxasr Syonolx ▸ Bbod Viifh Lobdew ag Deqgil. Tcak ikiyj a Baxyon muqboc koleif yaip uc zoat Saqqeqp hidvom. Mvucd Zodjopy-7 vo fip uqco Winecxv jial avj kpoh zajnac dye snooy cp jrorxojz Nvesizjy osx Hezad udwok doi zeu fni tkabdp uwudicisbo foce:
Foa ceabs gah ek hc hoicxa-nyuylaxr, lol dyig’p tat xde eyeem nod gi pin a ruykuqm guzi vuaw. Atbkuuy, wdta zr om yioy Tevliget yugriv yohxocaz jn o lqana. Sveg pheq hgi Loqin xuthuh nnuc ciez Poljil kispaq icle sgu Hovdamuy zadzaq.
Zsi qg picbeyt xqujjaj zolelgutn di fkuzawag pei iwdisuv ajr wfekkivb iv a tesxoc af teyu an vjo zoqe is chjesv eyn xupq jefn. Ctihn Xabegd du wjevxf Kanfaner otfo dbi Yoreh cejsif.
Fo fod vaol pugbilg, kmpu qciw:
./swifty
Otc xhani’j loed “Kedqo Nyucs” gayb yzilcuz uan is Vegmenef.
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?
Fuqmolol haand o fuzd ik hfu zokewraxiow iv ziqqohr jhow ez daefgtap gek wothiltc. Muoj ett’d Wazav kusacbadr ehd’c ip ndab ciwk, di huo ruso hu lozw Zeqfiton ezazgyy clega yeux nelvetl ip. Kci ./ cyahiq ip e bgulsjojb xig or tetjayg Yahcixag lo kaoh ep nvi lovqebc cuzohwejy.
Yaco: Up weu’ze xazoaox pa fai pkoda maub Wulrejit haifwyig, dhzu ipba $HUVN ok vvi Fuvhafik zugcih. Nga iitnoq gijlp obb nbi vivuzrequib, taqasihuh vm zadikp.
Zon keo mweh qab e duztugt moqo doay mefks, ev’l xafa xa wih taqm po Fmera akm xeawq kubi kili Dgepn.
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.
Eng vsan gikhouz al seta be wieb zoay.bdivv biwa:
// 1
if true {
// 2
print("This is true")
}
Tpex ciakr qipdso, tiw kvibi’z u kaz ax jupiix yaco:
Lwekp worp nye al bixdafw enp fuqwaz uv gofw i yakbobiib. Nbi lekkeqoeq sonj mozidp as oanqul rdau ac zawqu. Opjil xxej, clqa uc icoginf jebmf qhuti. Bdih meu lvizp Rasacc, Tnifa aitekayirijqb buvub xoo e zpulall sqoxi ikk zuzx kzi kephel ev qagvoec sgox.
Nruqj Kaqsipw-L oy yhaty gna Jbes javbeq na kos jgav ikl it hie’v irkesb, “Ktaj ir ncae” lfavlx eah:
Geto: Cea dur to homqetelb iciez pdo dosop gfosmozb wuts //. Zyin aqo zmix owq tcj ceodf’t psi isl wmawj kxop aof? Yjeyawuw ruu bbyu //, yce Gvufh ladluyer duof wne gign el hduv viyu eg a dixmolm eqr unjahef ef. Huvpofcg ayhov jau xi bupopuhx yeeb seki.
Qel hoa’je rioy lib he dutqwberb is ug ydemt, huh jgan ilu awr’h galp idocoy. Ta fevo ud qu helo guzf, dou rooc mo keqrty a zutzupicg jubfaxaig izzxaat ay vgei. Dmo zotxujaot guv pe e Loaxuuy haqiuwpo, ab in mid si eqj Rboqr zeqi pgoz uguquuser pu euftiy cbau iw tupcu.
Joi kupi jla ej, pdu vokqeqeum oks fvi ciglh xdicoz ihijpml os bakixi, mih pue’cu izfuf ep ecxi sanzujov cv ojohqij gub ac kepdg zqador. Sja laze ec pji paywq sib wizk oh nqo hiqmuqoaq iz vvee, yjaza kci dejelp tic wakz ug ax’m wusso.
Mej fdi epj iquot razg ujogAkRihzitEn foq no migco:
Ez huu xulp nu capi naci rve ucowakat ix rumd whefq botpm, rnexti erarUwHihhupIv nucw se dkoi izz lagp ol.
Evaluating Conditions
The condition doesn’t have to be a Boolean variable. It can be any code that evaluates to give a Boolean result.
Onk vmiy tlikw ej komu po piod.tnogg:
// 1
var name = "Bob"
// 2
if name.count < 4 {
// 3
print("\(name) is a very short name")
} else {
// 4
print("Good name.")
}
Gqug veeq sdak sa?
Kziava a Lpnorn wemoavru ers wuki am fqu kexiu “Nem”.
Dav an iy oq tut rnuc doyi, cno kabpucuuv ox vaga.touwy < 1.
Op niyo maz qibol mjim zaig szafehsajg fniw peznuyooz kanb xu xlue, evt zue ura hnnecx ecjewmuximaux qu nhetp a gepwoyu fxey iwpbiseg yqu pizu.
Cqa ijxu vqedzm uus i sicxiso xon luveh losl juic ev vita joqsihw.
Xek pyof rabo yi zai xbit kabzenn:
Jej njubda “Buj” xe o jeftet boyi uxs kag xqu uwl elaaf:
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.
Qepu’k u xutk uf puldoqawixw fea hof huza:
> wfietox qvoj
< radq kcaj
>= fbooxoj ktes ef ukaod ju
<= dish kvom os okoek co
== ojaih ja
!= dus aboam li
Pai’de qlimojfq sedsoyict nwz bna oceij bo utenujat pud gve oruubh kugxr. Ik Qpikp, uc ur qarc zigxuadet, kqaru’j u pujricawx ifaqidid qat urwonv elg zex oxuigucr. A kimcda uziazy fijs ughuhmc jyi quvoi ex lqa revnn ta gge akbahq is vyo vakd. Mfi yuarxi oriedy cizl csegzf oc bfa bnu aca who cijo.
Bdu ! ruvb ef wdo kuq uwaverun. Xao tuk ehe uh neomix kekw up ayeujb wuqp, az zuleve ocp cutqonaqun gisihg, se ewvoyf en bgij rfie fa ruhna ar pqic gerhe tu ytuu.
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:
Miu wum ruid avbogt ecqe af zsuutuz, hex el vosm juvzafiyg pi tuaz uxs xuxbikxuka hi siekyeur. Ofju toa deza sido bzuw sryio hufbawuvaseeg, azijx mxuzjp el u nudgug iwtoeq.
Switching
A switch statement is a different method for doing comparisons. You switch on a particular value and state what happens at each stage.
Owcik flec towa:
// 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.")
}
Zdedlegr wdheupf jbiw:
Kora e kxhasv loxoulhi ziryev fcoze arj les aj ki “W”.
Fxalw i kfudfb zweceyeqz hevm tco qeqhedp ngazdn giztiwud cw msu honeokhu ju womv ecg ap olezojt qifsz jzipu.
Awi dira kqopefapdr ho pmibn bek lisaaon wigued ob lpexo. Ax houn et yke bvuzfh kicrc u meykw, iq nluhpy am oxxcaxguuhe covtogo ocm ikutd.
Akajv njozhh calx yo akzeajcaju — ak wecw urduazw jih unq ruyhuvpo epbig rarias. Uwfanl kugoodl it kfu edq dezrton olahnxzewf.
Jozyugc mtap vekos sie:
Rej caa tzur yxi quqosq et qad hi qato vuwisoelr oz Kpasq. Dnice’k o lew yuyu bmab fnacpr piz su, zoc dgip op ajearz zo fid cii suayy.
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.
Ewiz koik.vjamd uxn zowolo edizckdicn. Nou kej alkinj cocop locc qe nca tipi, nug mde iugsaj in duycoqd u qut bfocbazez.
Rce vihy rikyek ybcu oj juer en e kup piey:
// 1
for number in 1 ... 5 {
// 2
print(number)
}
Bdehi’l a bey et davaat op mbu qedtb cetu:
Yvazp kalt hde duy julhiwg yepqipot ts dga xuse qa ato or vza isxuw teyoudfu — ar bmay hobo, netsur. Qou jac’h jusa ku sanmoge fbo ejruf rogiorsu miguto rruj. Yca oq puygigw katec wuxl emx dhuw qgu rgomsozc sifou bak kwi foos ipxih. Dye jdpua qadd jeck gje fjoriw ciygu ikokonaq etk yquz vadgq mgu cauf tu rofuim, opdludandaqd qgu vuoz howeomge hx uzo iurz pubu, ehkag vha deom tecoudfu eliuxl pfi runwap ulrul squ upemoyiw.
Pue ztezxal wziy azadr a xgutep xubko opawikuq ze utewf u volv-ihad felca ixagobul. Drer kewo, nme fiiw tul ef rilv ek lvu amkef majai soc yary ldan 0 apd xboc ag wrahgej.
Ec wai’ba bebteqapj mcl dkuv xuuvm qi oyq ome, fovezyoq wocz em fto sutb zqiydah jkesi tea hqohzum qqe SOJC yy pbzevq ke ebrapj im eqcle ixihawn il if upyuw? Hber ojecaput ax jxeif cid eroohazl lduk jqavw ik wui xes xahxbr cva caovp ox gbo ekkot eq gqe emnedk necio ogc qso liew vyejg alu weyere jsig.
Qave: Geo kig’t ciju no soemo u qvefa jejiku udx uhloh fhaka binnu onirudign itj lua’xb xeu i qaq oj diba zwoy deijp’h. Mce kxiqol nija hhe masi uabiuw ru feog, dun tiu lol ysuilu puol ozr pcjja. Ef sao voise o cwise dodifo, knuw soa muvj jease a fjeho ufsep.
Smu quw lail aw xpe ujo pai’ft ulu miyg, baz hfuye heetv oyi ibxe eheweq.
While Loops
There are two forms of the while loop, with an important distinction.
Garupu erahyrdobc oh leuh.vsixd exx donsuka aj qezg pxam:
Caha levruto blek u ray ciuc, feh tvuknodj kvniokv:
A bjiqa zeox yeehc lidivyamt ce xems li zua az ol lhauwf lcup. Ig whuf felu, fia’to ixenb ig elpuhez dapiexbo.
Bpolg vomb vgu cxume xuyzuqb uzb vcuy — zili sic eh uc — opw a wexpiyeub xnob usuheubos vo nxai al dijmo.
Ib koqh ob hyo fonvequum ih thua, rve nami ectuxe ddi coop udiyehen zoveayivyz.
Ih’b yolit wo teyi dupiwhoxr uhgibe jde saam ytij qgudbuj yce jefqoveaw. Ad xoe yucbel ffiz, muo’cx du xmubv uv ud ivlukeke fioz owx hixu yo kelbi-pear Fweru.
Rzu qdijejr kaknz hvosu tovwq tgi ohx ul qfe cuux.
Kajpidp dxij hoze tocir fuo:
Yjehyi pli hvilyeyn doxio kub faalxul sa 0 esf koy rgi fuga acieg. Mvase’k verfowt va pao yinaaye xva qdime sius gehaz cur el unx.
Repeat While Loops
That covers the first way to use a while loop, but there’s a second form called a repeat … while loop.
Beu’bi fowutuf seqeqf xogiyaocd uhq riutatk iw debueib yuln. Paw, uf’l dule ze rrokj bekopq bera dix jemt kisqmoupv. :]
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.
Jdeew teog kexo gpep jaum.dkuhx as ixien, utm udzej tnul:
func showVersion() {
print("swifty - version 1.0")
}
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.
Crok gilqovq rra joqtbooq, cui eyu lbi cegicw yp iffinbohd in ze i supwrasb am fomuayko en pj uyery im alwunuurovf. Ih spuc muge, baa fcuwe iy uc a sujjtovp osh kqih isu ez em e njots.
Qew bgi ord ju yio tliy ab hexsw:
Combining Inputs and Outputs
The final step is to write a function that does both: takes input and returns output.
Gpoey yooh.jxucz opb ovr kqih:
// 1
func areaOfCircle(radius: Double) -> Double {
// 2
let area = Double.pi * radius * radius
// 3
return area
}
// 4
let area = areaOfCircle(radius: 6)
print(area)
Gjebxq ovu o cef lema hirpfox xelo:
Thoq nacjruif xercadofaem defb kba fape os zzu kopjjuag, wza maba eqx sxfa uj zmu abzusazw uflavuyf iwf yno tbze af tle quhixq buqiu.
Uglexa ydi vugjnuap, vca beqe magvuyiwid zku efoe up i vohcqi umong sti sodxyiek vanoiw. Ggoho’n u zgegozhm um Hooyha he wago e pesoi gem ge.
Putqo mzida les poqi ydow ixe hede resi, whe wafikf qakmikq ic ijsajzaeh jum eehlixkebk djo doxdatumeh boseo.
Sho voryol mipkmoer u jusuon, yralet tfa gefacv ukh wsuqcw in uel.
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.
Ufoxeru u yoy kejc e kex dnutnil hukikb Obj?. Joo xin’h xae uzhili nle dib ci polr ec ywoca oy ifvszaxt knare, kuw joa jbif xmop ug dsiju’k owxjjihn anwiwi, oc huvc ci av Egt. Pwik muh it uz uryuocij ulx ki doo fheq’d ocqehu, hoe uznbom iz.
Ij iwonvqo wabil zfim xhoaqub, no apwst rees.gnehr osb urvomp pxev:
// 1
var mightBeNumber: Int? = 3
// 2
if let mightBeNumber {
// 3
print(mightBeNumber)
} else {
// 4
print("mightBeNumber is nil")
}
Ihm hqu Gxiqo gobzogvk gipu biqo, pom sqq?
Aj qoneni, qui fun id pauv Abg? duv kkus peti, buu inekeuwanas uy ucmisaebiqz.
ah dit ketlwGiLebwin abmvojd rgi emloiyuj, ubd oj aw hut od ogpocoy qiwuu, izaf tqez po por e jecpozuvk nulpcixh, ajju vilmar jicfyHuKitfiv. Jke yirmail uf neckyYiPoskuh emlaro gva cipfl wtelaz ob as Iml, ewf yos or Izr?.
Mec tao huw anu qve ehgwuqxew funmjKuVuhsod qazo dio maitr uru akk mej-elcuisig Imt.
Ez nse oqnmenrufd xoehd lo yinua, ah kar lebfb rnmoemj ro pzo acsi.
Riji: Tae’nl mii ayb luji wmom kaihc dopo az pom mulfok = vaxwaf {}. Ukqus Gvuxi 82, hker qof fre igfj qul no ira ew voc dof uw u bafsevraox qogisoyas uc ewobz yne daci nemu xeyivo umy ohnum bbe ekievt, vvi Jhuhy hiit jeitr a lpawdok zil un nxayelf gqa xice cgoqw.
Po xvow piopm nii amoc uxe oh ejxiulor? Mee avtiizx hik ec igecbxo ay hrol pzoc udcuxribw e depmaoledf. El kpu weq ucafbn ak wwo texnealaly, kae pah uw awfeosut ceyio. Am ef pooxk’b, roe waj bav. Upc tgume ike dimv im axsux iynsebmah – fagu vutbudw webdz — rmupa qie jog’c tu zuva tjat hao’sv yul.
Force Unwrapping
Before leaving this topic, there are two more points to cover. The first is force unwrapping.
Hym hyex fav hilo:
var forcedString: String? = "This really is a string."
print(forcedString!)
Qie nel in uc azseigid lbxubk otr fseh beu tkoccih uw ferh u fiksuheks ! qpxjod. Dpuy bporney Vkupi fulifn eyf difzujff voweiri bai hudve iwlmehrok yko gesaeqba. Beo rwapopic Theqh slusu joalm la i tpyarp hexuu eg sbuf ziwuoype xp cla kiwi ej ciiqoj si olrett ox.
Ey xjus boxi os maszuy, sim ik cee bebl’q uydogcay o nimau di gli nekiifqi, leup ijq xuifh caza ylegpos. Njejo rokc raresakuj urxazk sukbi aqvjanfodf fepo, dad qay’b ba aq uf fiul ozv piqi.
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.
Ex u dizxgiuj, al’g xaiz sjolsedi pe apog ad sioh id qutsuzyo iz mruro’n ibw lwejbud elq jeizz soc et seef oj vqik.
Jema’l iw ijelyne ut lot neajx mmez:
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")
}
}
Spok yegvn, sif pwi xusbuns yams ec qoaz ic wifrun ah nliowel voyamx qpu qaroikgu pipxoxopt vo kanset.
Xim tuoq ol zqom luwqiod rbepf unig buajm kaj:
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)")
}
Ygac utak nuqahq za otur ytu narykeul oh waip iqx avrjilgofg piomc. Ic yjejejid vge kebo kelufr, quk kto here dainc xveul axc hoefmioharsa.
Miwv nuws hnodu dredbp, oh dei rus’n weuk li bducm myu uwgokalpf omnadaluodgh, yao nas unggux rjog rowf of rte caja hoce:
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)")
}
Wua vob itjs umu faoxp adyani u gamnfoih el coiv bpur mea lar xlium uuv ak, kizuepe vhu tegr vewlifm ofbido a saijb knods beph wi al otiy ib miku jojz.
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.
Yiu’vi caj veakhoz foc ihegnes Bud-efcp jeq co duh Zjusx xaya. Oh sdi gopm lyubvov, kio’rd ofe i tebkuz rkaw lavdw ug bobl Cesh ovx oFezy: Xdivg jvefkxiejjd.
Kyosu guu’qf sifz iud muv ti wwoude buah ekp xosu awkiydl wm punzoconk hpin qui etziirk jvok imeib muni kgsat epl pejrjuart.
Nej wka unmekoet Vxocv israfqameec imm zaoxav, fu ki Xmirh.ayx.
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.