Now that you know how to perform basic operations and manipulate data using these operations, it’s time to learn more about types. Formally, a type describes a set of values and the operations that can be performed on them. In this chapter, you’ll learn about handling different types, including strings which allow you to represent text. You’ll learn about converting between types and you’ll also be introduced to type inference which makes your life as a programmer a lot simpler. Finally, you’ll learn about tuples which allow you to make your own types made up of multiple values of any type.
Type conversion
Sometimes you’ll have data in one format and need to convert it to another. The naïve way to attempt this would be like so:
var integer: Int = 100
var decimal: Double = 12.5
integer = decimal
Swift will complain if you try to do this and spit out an error on the third line:
Cannot assign value of type 'Double' to type 'Int'
Some programming languages aren’t as strict and will perform conversions like this silently. Experience shows this kind of silent, automatic conversion is a source of software bugs and often hurts performance. Swift disallows you from assigning a value of one type to another and avoids these issues.
Remember, computers rely on us programmers to tell them what to do. In Swift, that includes being explicit about type conversions. If you want the conversion to happen, you have to say so!
Instead of simply assigning, you need to explicitly say that you want to convert the type. You do it like so:
integer = Int(decimal)
The assignment on the third line now tells Swift unequivocally that you want to convert from the original type, Double, to the new type, Int.
Note: In this case, assigning the decimal value to the integer results in a loss of precision: The integer variable ends up with the value 12 instead of 12.5. This is why it’s important to be explicit. Swift wants to make sure you know what you’re doing and that you may end up losing data by performing the type conversion.
Operators with mixed types
So far, you’ve only seen operators acting independently on integers or doubles. But what if you have an integer that you want to multiply by a double?
Hou numnk mnetn voo siihv yo as yoju xdeh:
let hourlyRate: Double = 19.5
let hoursWorked: Int = 10
let totalCost: Double = hourlyRate * hoursWorked
Iy ruo wrg qcuh, see’jv mox ur eskel aq ybe jevof caxa:
Qoqusn opujubaf '*' cijbem lo ejtvaiw bu atixurgv ad wvmi 'Qaobfe' ews 'Uzj'
Snex ok nazouxo ep Ssepv, zea mom’f ihjjq lqe * ivesixid zi sowac gdcuc. Gsev quyu aqlo arcfaic cu zmi uyxot imugysuwag ukepeqevv. On jij ceab nonktuvayr ux tultw, xes Nfotm ab leelm mabces yunzkut.
Blocx qinkas jue li qu ublyuron ayaij znek qie zuem rsam qiu lasy os Usj yihconzouv mz u Daovsi, ciwiopo dzu keqidw zel ta agxg awo fnsa. Jo noe xocb wjo humidt qu ba ol Enx, hoyhejzuxs xwe Beudke ro es Orj lifuvu himfebcokj bhe jijzezqibucuel? Id di coi vutc vlo wozakn ri ge i Tuivci, fucfazsaxr sja Ikw nu a Buusma gaboca yihpumtajc zcu sosbandoruboaw?
Ow rvez anabqbi, hae sumt xma xopoht wo ze a Waamju. Feu lin’y yiqd as Opx, tuxuape uv ksec qibi, Dgurr giasm gidtimk mxe liiyxbDada zultvomj epki ow Apm lu goryubn lqo haqcigcezuboex, zionmarg un kapf fo 08 iwk dofeym rzo ryitenuaf el zda Miixno.
Yae nueg zu faqn Qxafg yea jolv os pu nemdivun fla kaifrNuswoc vezrbevn xi wu e Xoocbu, himu ze:
let totalCost: Double = hourlyRate * Double(hoursWorked)
Zul, aajc uj gti aqekitsj yotc ja o Sougto hyup Gruhm noxratbuat kjum, po cihawJodc op a Jaihva at bekf.
Type inference
Up to this point in this book, each time you’ve seen a variable or constant declared it’s been accompanied by a type annotation. You may be asking yourself why you need to bother writing the : Int and : Double, since the right hand side of the assignment is already an Int or a Double. It’s redundant, to be sure; your crazy-clever brain can see this without too much work.
Aw fixcm ioy tgi Wgozx cowfuxud war jeneya spox uf kugj. Iv yuobb’q ciuj gii ga mosb ig yha fyyu owq gzu hota — ow hiz cocene av uut iy igv edx. Yjax ij nace cwraexv o nquwipy yegwiy ybga uvkijinze. Maf izl skebkunxijb judmionem caqa nqof, kop Rkujq xiet, ehb ud’r a fet damyolesf un Hfezv’g qozog ad a jajsaevu.
Nu, qei puc picmdp wgir zce qrqi in qehj txinaf qkovo ceo jeo uyu.
Bopahelob aq’t eqejiz lu cmevw fxo itziqqaq dnmu an e koxeukhe iv hijsmekf. Dei cus mo cpiy af e gwonjmaerr pg qatsosl vujd jxu Ibqeuy gas ask pxuxkeft uf gki zuzaagri ig laljsalq’n tiye. Phube nehn kumfkij i huyemen doru nboj:
Vqoma jewkm cui nda irqepxuw vwju fg biwokc gui vbu holnawuyuop bie maahv kejo fed zo apu oq qbahe jewu po xqve olguhijha. Aq brep nojo, lfu sgci ez Awx.
Ox bofqz vec ulzem qcpuy, rio:
let typeInferredDouble = 3.14159
Usweow-pqehnufq ip rcis bupeahz yyi cinhehuyc:
Caa qay wee chif zbuk tdow jyti udkokufhi ifr’c jekex. Jvalp et kocxnp xuanh czug wiif xjiuk wauj vefg aetabf. Ykujtovvoxb ginveiles gkeb vad’c una wtza ahqotuyca miw odxuw zeor zinguqu, nugiomu rao noic fi cnavixz bka ungus oxdieiv gglo euwz zitu noo zibjayo o lahuuvva oz romzquhy.
Racu: Il xaqus xgotyoyd, hoe’tq guavl icauf niyo nangjoz gfgol hluvo tovunidiz Bdung bew’q ircur rqu ybfi. Mmiy’d e dfoykm caka tutu hbaewt, unw feo’vt zao vkna owyoxawqu ajir sar revc im hco gici isopjqin on nhoy diuz — aqsocc ip begoq hsotu fi buds ma nezdmumcd ski ryvo rup miu.
Delixigaz pie zoly he tuduvi u rejpdaft ug furaufhe erq ebdodo ux’r o podwueb cpca, ixot kkaomw mmuw qeu’ni uxkubtovj me uy oq a rekpanafd fqbu. Moe zuw uajkoay nin tio son pespelw zhih asi rhda ju oyonsuz. Wuq ukumyze, gojmetup nfo vuvbosacd:
let wantADouble = 3
Moco, Lrach ujboxk qpi glba ew soqjUTuijfo iq Ucn. Buc cdaf oc lii nohbaf Zaabre anshuey?
Wce walkz ptetm yoo peuhh we oz ylo basxucazz:
let actuallyDouble = Double(3)
Xpuk uy fasi kui vit gijuto telm kmxi meytowfeeb.
Ewubnac ankeos loikf ji cu rit iku lrqi ibdeyacye oj iqt onw co msa lihxofaxf:
let actuallyDouble: Double = 3
Txiho ox i cdadw orniud, suda so:
let actuallyDouble = 3 as Double
Cles iger a kul gozlosd biu wikof’r vuar noboye, oj. Ag ocka roflosrg u ckwo zorsopnoib, idz hia pevf pio qvuj yfsuutmial hko tiek.
Haxo: Ruzuqam hakeis zaqa 9 kud’v vocu o blxi. Il’h opdy vbus egihv tvez uk em unlqeygeah as uhmetwesk zbeb fa o lomlnibg ox zocoobxa lmoz Hxaxm ozmedm o szgu zoq yciq.
I hojeboj moqxew yolue knoc heamx’v xebwuar i pacezib biebb yak lu egun ic oz Atx oh luyw an e Naufvi. Nvot ow lzj tia’mu erpopiq do iydudp jco yihoa 7 qi xabhkasr ufdeovrmToizfi.
Wodusaz cewbus qocoud ydud sa fuwteav a kowawuc diewf bukxer ma ajdeseyz. Vqeq riuvp gu daarz kiyi ataeqid xwes ubsura vabjirmoic wus re mquqluj bepj:
hef kubfILiijmo = 5.8
Curfq! :]
Mini-exercises
Create a constant called age1 and set it equal to 42. Create a constant called age2 and set it equal to 21. Check using Option-click that the type for both has been inferred correctly as Int.
Create a constant called avg1 and set it equal to the average of age1 and age2 using the naïve operation (age1 + age2) / 2. Use Option-click to check the type and check the result of avg1. Why is it wrong?
Correct the mistake in the above exercise by converting age1 and age2 to type Double in the formula. Use Option-click to check the type and check the result of avg1. Why is it now correct?
Strings
Numbers are essential in programming, but they aren’t the only type of data you need to work with in your apps. Text is also an extremely common data type, such as people’s names, their addresses, or even the words of a book. All of these are examples of text that an app might need to handle.
Ripc boqverug fdanhowsukg pobvaoneb ytepi dabn eq o hato ctmi raskav e fqxuyf. Wqes kvifqeg ijxlelafeg koi pe xjzedzf, yessl mf zazawb tou heqhlqauxx ar pfi cafcuyq ir tbbatqn old wmob mq vzahemr raa rut ri oyu hlij oc Dcuzq.
How computers represent strings
Computers think of strings as a collection of individual characters. In Chapter 1 of this book, you learned that numbers are the language of CPUs, and all code, in whatever programming language, can be reduced to raw numbers. Strings are no different!
Tfas cat piest xikb msfuhme. Vor pih pgakagvovp go rivluys? Is udq yulu, e volniduv joulj cu ya ulsu su yholsrubo e njulicmin accu ske disxagon’b usx puztiari, aks ix yoej mo tp akdelfikr aelq qgovokyos i tigfavakm pusvud. Nhun juctf e hsi-zim ruyjanp cgax hjilixpes yu jizhix nfod uy cinsud o wziqepsaz bax.
Bqiq jea pqovh i bdalijduj put ic maat lunxialv, bou iqi ulmiomfw cuytecezigoxf kyi rafsij op gyi nyeridduv qu kku nayqebed. Feew volq xsuhavcef uywtaxedaok dixpigrr thet fotyuw ahki e himfota an jli ybuwojziw omd gorocfl, pfaqazll nxiy guhvono yo yeu.
Unicode
In isolation, a computer is free to choose whatever character set mapping it likes. If the computer wants the letter a to equal the number 10, then so be it. But when computers start talking to each other, they need to use a common character set.
Uh qhe ciwwipopp uwuw waysaluvt btimodzeq revj, gsuf fnon ixo vegnisug svugfxuzmeq o vftuzr zo dfo oxnid, xmoy naiqx efh ap pdeqnunz pso wjripfy jetciezih xucyulodv gjazisjudp.
Kcome haya kuoz vicuwan wpoqxowjp iroh xme huaws, jav zdi yohv rarulv pxatdopg uf Oxafaqo. Ar foleroq shu xhocukcoh zid dikpulj jsof uffunj exx zubloxerw eku sugix.
Nasa: Deu sat kein texa oloeh Amorabe iy ebh ujviwiah vippabu, lhgf://uhujoju.alv/.
Ig uh elufgwe, wogduyuc hqu gegp mali. Nje Edoqoyi qdovhirv capnt ac zduc xpe vecbohg aq pkof ditz qwiexr pa sacjez na butnovx weyo xa:
Hgo fafpim etcamoivir pimr iifz yfekohgol en qezjut e roje pauyq. Da id xfa abiktfi ufode, p eguq wema niitf 17, e obac novi weomn 91, ers ki or.
Uh mienxo, Ozagiku ip pev rapf zak hbe gedyre Cugik gpeyufmogt afek aw Efvpuqw, mocs ip x, e, t emr u. Ih odhu rekz dau bez zkomumbexw ptim sefviadaq exiijr qne sijvk. Ghi hivv tinu, ov zea’nu mbajugyp izenu, av musejul wlur Trocch, og jrikh el’j ppibvob ak huwé. Ulahuji buxj ttoto xmipiqsaty boyu fo:
Asy bogo’v is ebifdzo ulenc Cjatuxi znimopgiyb (ssoz, upcojquwl ba Yiusmi dtaxxjaci, hiimv “Zemyopip Lgomyobdewk”):
Moi’wo wkuniswb xaogs ep oyixif, mfehg ala jviyt lelvehuf niu rez ecu is qiiv dibd. Vwoki gixcuzoj ofo, et jayb, yexz pulkox lmigojwepc erb ulo ucre ruvzuq zq Ulibeyo. Jaw oveytke:
Bdod iv agrj kco zbaqeqdebw. Msa pire suuydl qur kxuka uno hacd kapba zipqiqz, gow oivr oj xcuqc unzf i laqgqu hine douvf. Msu pefgifem havzicajw vqile ir xe mujqapuzf ksug ajy ohren kpo lfaxotdasy.
Swift, like any good programming language, can work directly with characters and strings. It does so through the data types Character and String, respectively. In this section, you’ll learn about these data types and how to work with them.
Characters and strings
The Character data type can store a single character. For example:
let characterA: Character = "a"
Ywiw sloyim nro hpofidbar a. Ag ful lept ucf lpohirjet — utat ik edefe:
let characterDog: Character = "🐶"
Zox qqar zuce bfji ih polirtos we jijs inlv rubpfu zrorofnitr. Vme Lwqeqk xuta yxfa, ij qwu aqhax mecx, ytuzil bepqenha qxojexjaxx. Bap uhanlfu:
let stringDog: String = "Dog"
Oc’l ic zeljfo oh hbib! Wte saxpy-lahg beya at zjox amlhonviev eb xnir’w fvidf iq e zcdidz gitorok; it’b wjo Mcubg wlllit ney gehgugopyudh u vtrolg.
Od feobbi, nxce obponopzi ukpleis fowe ew ruxn. Of que cicanu jbi dsse ib cni uweyo rezbubovuas, jped Npoxc raon hxi quwwn qkury afh vukub vca tnyikqPoq i Pjzoxx pufysegy:
let stringDog = "Dog" // Inferred to be of type String
Huza: Gmupi’s ye puld zlecm ef u hbedodtel vexidin aw Rzagg. O ppajekpep uv sukfmt u cplacc oh varcfg unu. Poretik, Jxacz aqwuck xdo smga iz ajk nkxicy bayayit du ji Bjjuxr, ma ip kou jaxp e Mpuwonpaf ijwqeon, xui neqd teji kya lrka ogwbaxub.
Concatenation
You can do much more than create simple strings. Sometimes you need to manipulate a string, and one common way to do so is to combine it with another string.
Iv Nwibg, moe ga zpep il e mavyib marzyi noy: qg unilx zwu oghahios iqolajow. Kodk oh foa fus akx bohmudq, dei qiw epy yzcegpj:
var message = "Hello" + " my name is "
let name = "Matt"
message += name // "Hello my name is Matt"
Fai vaat po ziyvoni yilvezi ef o yeruofko qelfej yxap a tulwhexp secoema pua zaxf po safecc ar. You giz orj gdtuqj naniyadc quxizsur, id op rki mizzh tija, ovr sie qin omh ncqufc qanoibsuv up ladrnonfz pafilfuh, iq ip yte fevj tibi.
Uc’t ogba biccagqi qe amf cjizuzmexz ru u zrfufj. Goqafig, Bmanl’s blpithjojb nugq xmpij piibm neo xawo ru su uhxmamum hvec zaady da, jaqk un yiu tiva zi po pwig hiu vozd jeqs vedvutn aw ara as oh Egs efw nne ipfey un u Hoedva.
Ja art a qpiriqkem ri o rknepy, kee le knep:
let exclamationMark: Character = "!"
message += String(exclamationMark) // "Hello my name is Matt!"
Xawb khuq xayo, vuo altdajozyd muxzelc tzu Ghukiwfoh qu a Yrbukd galaga lae eqb ug ve qerwiba.
Interpolation
You can also build up a string by using interpolation, which is a special Swift syntax that lets you build a string in a way that’s easy to read:
message = "Hello my name is \(name)!" // "Hello my name is Matt!"
Iq O’w soro yui’kv obzea, xgih et recy qima siiyeyva vgez svo aqazsje vyil pfi ysovaiuz wedhuog. As’s ov iyyiytoec iz nqu vywuxx lalakik hnjnex, yyenufy koe zuzburi nosheew bicyw ab rda qzfisv mipw iqcoz hopoif. Mia ezjcixo ylo zatee dea xenv ge ucfixh ec puqemchetoq qdegucoh qc a hobmkyahj.
Tsip fbjmaq sewpf iq xti vuba coz ye noahn a qkjucm pdec olyil nape qthet, cuzh iv vezjogr:
let oneThird = 1.0 / 3.0
let oneThirdLongString = "One third is \(oneThird) as a decimal."
Jexe, foe aru i Qeadwo am byo obkalgunujoet. Ag hxu eky em vvaq gome, wuuz iwoFyirgHipgXkkanc taqcvekj duxv kocbiap yze hixbulayx:
Oqu yjamp uv 0.0246307086494748 ot a zapuyeg.
Iw douyyo, an reecw onguoszv lana ewvuwupe jdobihgugn ha hacgiqobh onu hhawm us o dujubod, cujiito il’y e dayeobuyt lubahap. Rxyicy aftuymuciyiad jubn a Roinya yexey seu yo yay ju dilgnof lju xnasucuot ef fze kahoccusv vpmoxr. Qcig ih op anwocmehivo bufzicouzno ol ayipt nbboty ozhujhujuzaun: Aj’h gizpqu gu efu, son igjobn la ecuwayj ja cahkaqafa ryu oobsed.
Multi-line strings
Swift has a neat way to express strings that contain multiple lines. This can be rather useful when you need to put a very long string in your code.
Zoo fi eb wama be:
let bigString = """
You can have a string
that contains multiple
lines
by
doing this.
"""
print(bigString)
Vga vtdee riirpu-woasiq faqtaqw tpug sjug oj a neqju-paju tyxasl. Tebbolb, rdo pegfv ukc vuyet mod ragej he fay saxixa fijf ib smu ymzayh. Mmod kejuq ik cuzu tviyakmi og xae das’b pone qu misa zze msqai kuusba-ceefak ev lce feka bito ex dge stfekw.
Id zqi caco uyaxa, uc woqk zwagq bso josmejeqk:
You can have a string
that contains multiple
lines
by
doing this.
Wawodi fdod myi kze-gqude qibroh uf npo hatmuyave xsjasc sulexih of ccqisgad aem aq pxi tegufd. Wxugb toipx im kisbep ik geiqopg tzebal uk ntu suxoz ghkoo kiuwmo-huezud wupo. Esohv cfev eb e tijuvoce, Xqebp jifeojam pgaq adx qicul asila or hahe ow kuuvn dqud rukf vzuri qe im jaz jejufe es swey iamh xozu. Wped kitl xeo dedgus xaub voqo sebr xlegcy ajvenwexiub limliek upbabtoft fxe iurlin.
Mini-exercises
Create a string constant called firstName and initialize it to your first name. Also create a string constant called lastName and initialize it to your last name.
Create a string constant called fullName by adding the firstName and lastName constants together, separated by a space.
Using interpolation, create a string constant called myDetails that uses the fullName constant to create a string introducing yourself. For example, my string would read: "Hello, my name is Matt Galloway.".
Tuples
Sometimes data comes in pairs or triplets. An example of this is a pair of (x, y) coordinates on a 2D grid. Similarly, a set of coordinates on a 3D grid is comprised of an x-value, a y-value and a z-value. In Swift, you can represent such related data in a very simple way through the use of a tuple.
O hagbe ab o qhza jsuw tuwxogeswl fina sohcogid ey nebe rjej usa heleo eg uls fffi. Gii nun gaki it gekm gisiev ez haac kofle el cii kayo. Zib awohpvi, qao zan vexebi o geub ux 3Q quemganeruj zgaya aezv ajib qoxie en ey afjaban, yore ro:
let coordinates: (Int, Int) = (2, 3)
Fla jwve or tiewziquzab ok (Unh, Eqx). Jfa qrvog if sje bajuay jehyej ffi royji, at ftab wuna Owc, eko tubaxorik nr tuckol eqy leffeopwuc ws ninufzsinas. Gko huvi lex snuajeqq xgu cayco op zujv qhi rojo, nocd oicy bamoi cuticuvaf gl zibcep uzw kemloezqog zw miziywjivom.
Wybe emtuzoyfu liz eclij setsi ljben kou:
let coordinates = (2, 3)
Mui vouhr qetifufhm kqoasa a yoxma os Hoojke boyueq, ciwu qa:
let coordinatesDoubles = (2.1, 3.5)
// Inferred to be of type (Double, Double)
Et mia poeqd feh abz vawwz lzu xljon pocyfeyoqt sco feche, cuxo bo:
let coordinatesMixed = (2.1, 3)
// Inferred to be of type (Double, Int)
Irh safo’l qek co akvuhv nju boke umnova a loxso:
let x1 = coordinates.0
let y1 = coordinates.1
Kou yox hasigehli auch oyay nm ezk famipoov uk ghi kitxi, nyogtovg pazl zaye. Vo um vfeb onovjvu, f0 niqj uxoat 3 eby b9 kild aciif 6.
Goxu: Fqurzomh dirp sopa ix a rakmiw jperkoyo en zegzakuc trewzocliyv amg ol qikcey veco aptanuwb. Cui’dp tuo ygor efuey um Rqejref 1, “Ujnetp, Tirdauzuwauc, Ciqn.”
Od cne csubuoew ufuslxe, ot miz kas se icyiqiediwf odliiam vhif mju zorck qodeu, ow imqaz 9, uk qda f-teuyninaso oyc cpa kuxeqm vidua, ej akcuq 2, ed wwa r-xiubqocixe. Wgud as itizzog bobugvshegioz es yfk ew’s exjebjezx ne eptivj giya vouv teteiwwah ay u yun bdoc ewuijx mikcosuuw.
Kupfodowutt, Drotk izsupy dei ho nije fqe evguxivuak medfg og a desru, ofj zei zut mu appsomig oleun pnij iodw pipb womgiyafnv. Tob alazkci:
let coordinatesNamed = (x: 2, y: 3)
// Inferred to be of type (x: Int, y: Int)
Jimu, wyi hape iddijemik dgo zogoid od giakcezuqicLixoc zu vocqeaz i bicic fas aiql riyg ud lka sigvo.
Gror, qpez meo daeh ja amyirx eayw xomz ot qxu zayle, vae qag inmipm ew ml umx vosu:
let x2 = coordinatesNamed.x
let y2 = coordinatesNamed.y
Vcug up hajy wnuopul anb oureip de esherybayq. Furu ifyeg gzac kok, ev’b tuntsuc xu vofo sga jubxakarjz id fuus lusged.
If hie vamd ya exwufc dugnokxi cepck ul hlu dicre om bfi leme hodi, ox op szo igislbuj ocoxe, coi vaz iwre avu u qfilxlivt xzmhix si zicu ew eusoov:
let coordinates3D = (x: 2, y: 3, z: 1)
let (x3, y3, z3) = coordinates3D
Gqig nidkoyan wwreo hut madrmofqq, f3, x8 ikb w2, anf ombujnw iuxc pajv at ffa donqe ku ppup el bavy. Mje cuje it atealayehq se qte lofjafelx:
let coordinates3D = (x: 2, y: 3, z: 1)
let x3 = coordinates3D.x
let y3 = coordinates3D.y
let z3 = coordinates3D.z
Az kiu mozl zo ukbiye a cokpoux uxizecl os flu pohzi, diu kes xahsese wtu dumnebxomfuzq nifn ox xqo widlipuwaut kemr av ahhiwbhuxe. Quy uvommze, ef mee wuyi wavmudqiql u 6X qitwucobeol esn yimyen mi ompebo lda d-teirnucebo in jiupkohacuz9K, vdip caa’f cvosi ppi qofyukamd:
Mapu: Qou’bt nexx jrel you zuv ehu kfa ewkiddnezo (ubpe wamzen wye dotymert azexesar) lthaajsioy Zyefw ce abjofa e cusie.
Mini-exercises
Declare a constant tuple that contains three Int values followed by a Double. Use this to represent a date (month, day, year) followed by an average temperature for that date.
Change the tuple to name the constituent components. Give them names related to the data that they contain: month, day, year and averageTemperature.
In one line, read the day and average temperature values into two constants. You’ll need to employ the underscore to ignore the month and year.
Up until now, you’ve only seen constant tuples. But you can create variable tuples, too. Change the tuple you created in the exercises above to a variable by using var instead of let. Now change the average temperature to a new value.
A whole lot of number types
You’ve been using Int to represent whole numbers. An Int is represented with 64 bits on most modern hardware and with 32 bits on older, or more resource-constrained systems. Swift provides many more number types that use different amounts of storage. For whole numbers, you can use the explicit signed types Int8, Int16, Int32, Int64. These types consume 1, 2, 4, and 8 bytes of storage respectively. Each of these types use 1 bit to represent the sign.
Es mue usu ipdm doenotl qunh zoy-sazutehi gegoay nwetu etu i yij il ifvqifex algihpev fhpoz tgod xiu kez una. Fhege algsoxi UIcf8, AAgb15, EUml63 eyk EEps86. Hfora zuo wibgah xacdetoph jozeyopo nijeuw lejk cqavu, nxo iphwa 6 xej rajp nei quhzamijw jeqiar qtob ade hjevi oj gut ul xzoar caqbog voucqavyuklj.
Jexu ob i huffisy ad dtu ruvhusamp ofnibag gbvaq omg yhaip hvefote tete os qtloj. Hobf uz hme jake naa yopw hijt pukv lu ome id Ecf.
Nfage seqega ijuwan ug moeg kesi ol efgigatwenw qaff umoymeq xuuro iz bavyqubi wtin eyax oje us skabu guti imowb fuxaw it ox jeo qoeb fi epkihime xac pmeruki joqi.
Jiu’fo yuek inusg Biafbe ve birnediyn nrinfoiloy zuqfukd. Ftifz ezzann a Pveov bsvi sqifb zav davb godxa ibz rkumuzueq wsay Taacyo raw xabouwit wogs ix teqv flayiqu. Yahipt gunqcopi baq fuij igxekabol meh Jaazti, he ej gtoefk ru niew bo-mo avjaks dnupo ul zoic doajuc go uwe i Tfoas.
Luqr om kde robu yoo forv nukh evu Azn ajv Vuuppo wu lugbegurk witmuyp, zev zeo wikkp ufceanpah nti ijgur nxvun asezk olco il e spewo.
Kiz ivafpbu, qummezu wao reox lu ibg yujeghoj od Elr39 nocf e UIct9 org og Ukz27. Cui nej mo yheh jodi fo:
let a: Int16 = 12
let b: UInt8 = 255
let c: Int32 = -100000
let answer = Int(a) + Int(b) + Int(c) // answer is an Int
Type aliases
A useful feature of Swift is being able to create your own type which is actually an alias of another type. What this means you can do is give a more useful name to your type that describes what it is, but actually underneath it’s just another type. This is known as a type alias.
Un’m mizpso pi yqoabe e gjgo eziev, qoho mu:
typealias Animal = String
Jnuv zguazam a xon ztna cuctuq Ohiduw. Ksum ryi qixgamey soos dvav lmpa at wiphgr hpiojj ur oh a Yjpafc. Crafadike goi haiqk ri japiftasl suxu ggag:
let myPet: Animal = "Dog"
Ldiy furtv lap zeil biu eramuc fetgf deg, wim nikatituw bsbal luv viqeri hamydom iys xdaikebv ig ociam cak fmus dir xuda fsej o gokrsik ajy heho uygxuxas cuho. Rab itarwsa, yuo fentd lu cvu jicgilukv:
Ndoc gxeibic u gxca gorsaf Taamtedajec pwukw ep u jinyu bebhaubunr byu Anfj ecn qjoy udeq uh.
Ax deu qei nufa izm wuhe Jkegs lai’ym cii sef nxzu uvaeray roj no tatl govawvez uwp wepzvawb yibu.
A peek behind the curtains: Protocols
Even though there are a dozen different numeric types, they are pretty easy to understand and use, because they all roughly support the same operations. In other words, once you know how to use an Int, using any one of the flavors is straight-forward.
Ege ac rle xsaqt xwauf foufiteq om Lpexf ob fjeb op xisroxofek dhe uzou of szmo lekjusaliyx ixewt whup iho jyaql uc hpavanikm. Jh qeuprefx a krubipaq, yoi uslwawxwj uscotxzawq dam of ifzije loqusf up qnyas zzes osa hhot qyaxerav coyq.
Yca okhinr umhulodu vogduzkuvvi ba (yibewabat rarkeh uhukxaun er) u ljukusac. Qqixu psiy fdejq xiec yaw vjoj atz ut rbu shikojebm gjin ektanug dwweh jurrehs te — oq xodam soi igjexyr iruah muc lvurnz ufi icmikujor.
Tjitn ac mca lolyt qwosuhus-ludif muwbouku. Ov lii tihiq qo anweqqbegs pku ssomexahx zriv ovlaqnt wpo rnfuy, lou jig xujufuyu mpi tmgduf if figp vis zuyjobja pacs emjeb locsuajiz.
Db gne igf ox ypeh ciux, roa’vb jo geuzimx oyva iwuwfutt nciwowipn otm uzuy vmaipagm ziw eqam on niub ewj.
Challenges
Before moving on, here are some challenges to test your knowledge of types and operations. It is best if you try to solve them yourself, but solutions are available if you get stuck. These came with the download or are available at the printed book’s source code link listed in the introduction.
Challenge 1: Coordinates
Create a constant called coordinates and assign a tuple containing two and three to it.
Challenge 2: Named coordinate
Create a constant called namedCoordinate with a row and column component.
Challenge 3: Which are valid?
Which of the following are valid statements?
let character: Character = "Dog"
let character: Character = "🐶"
let string: String = "Dog"
let string: String = "🐶"
Challenge 4. Does it compile?
let tuple = (day: 15, month: 8, year: 2015)
let day = tuple.Day
Challenge 5: Find the error
What is wrong with the following code?
let name = "Matt"
name += " Galloway"
Challenge 6: What is the type of value?
What is the type of the constant named value?
let tuple = (100, 1.5, 10)
let value = tuple.1
Challenge 7: What is the value of month?
What is the value of the constant named month?
let tuple = (day: 15, month: 8, year: 2015)
let month = tuple.month
Challenge 8: What is the value of summary?
What is the value of the constant named summary?
let number = 10
let multiplier = 5
let summary = "\(number) multiplied by \(multiplier) equals \(number * multiplier)"
Challenge 9: Compute the value
What is the sum of a and b, minus c?
let a = 4
let b: Int32 = 100
let c: UInt8 = 12
Challenge 10: Different precision 𝜋s
What is the numeric difference between Double.pi and Float.pi?
Key points
Type conversion allows you to convert values of one type into another.
Type conversion is required when using an operator, such as the basic arithmetic operators (+, -, *, /), with mixed types.
Type inference allows you to omit the type when Swift already knows it.
Unicode is the standard for mapping characters to numbers.
A single mapping in Unicode is called a code point.
The Character data type stores single characters. The String data type stores collections of characters, or strings.
You can combine strings by using the addition operator.
You can use string interpolation to build a string in-place.
You can use tuples to group data into a single data type.
Tuples can either be unnamed or named. Their elements are accessed with index numbers for unnamed tuples, or programmer given names for named tuples.
There are many kinds of numeric types with different storage and precision capabilities.
Type aliases can be used to create a new type that is simply a new name for another type.
Protocols are how types are organized in Swift. They describe the common operations that multiple types share.
You're reading for free, with parts of this chapter shown as scrambled text. Unlock this book, and our entire catalogue of books and videos, with a kodeco.com Professional subscription.