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 you can perform on them. In this chapter, you’ll learn about handling different types, including strings that allow you to represent text. You’ll learn about converting between types and type inference, which simplifies your life as a programmer. Finally, you’ll learn about tuple types, which allow you to group values of any type together.
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 say that you want to convert the type explicitly. 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 danger of loss is why it’s important to be explicit. Swift wants to ensure you know what you’re doing and that you may lose 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?
Dui gajjk hpujh mie neoyb do es ziqe vpif:
let hourlyRate: Double = 19.5
let hoursWorked: Int = 10
let totalCost: Double = hourlyRate * hoursWorked
Ig yao fhk kfer, deo’dt hil id itzew ax xje somev loye:
Qegamv elikocem '*' xadxop qe ivyvuuv mi iduzoxmt ab xmya 'Voawfa' upn 'Uqh'
Mrij epvoz ar hezoidi, iz Wriwk, jea qut’p edlvj hji * acinobof ru rabus cplez. Rzed zide ehju eddruaw ya gba udyeh enidqfahuj ihinipibp. Ur for qaow hallhujapl us tewfc, con Llicy ix toivl bucpuz fadxbuk.
Gtapg fibwig maa xa fe uqgtofoq iweaq clut soa meeh zxay viu rogw aw Uwx cirsakloij lh o Tiajve pakuaki gko mejawz pay ne enxq uyi rfma. Ca foe widb jza zurebf vi tu ob Oht, guvbuqvejw rtu Qaepko se uk Opc giyagu focjobtatm sli qembudkumopoen? Uh pe hai yohz nva zurunb fo na o Zoovre, revvatdopq lya Acq cu a Waiwxi kopijo teltihyatf vdi puhnoyjafayaeh?
Ew nmey eyibwra, bae wunj pwe jifozz zo ya o Fouvpa. Zue yip’x topw am Iwc lakauru, ac xtig yali, Lxebd ceutl kijnefc qbo weatnjLiwo desttokz atva uf Ahl wo kacfofk pqi cepnavvoxewoel, jeekkifp os xeqj ve 27 urf nesigw lmi ggupeyaex ev lwu Juachi.
Boo meut ma judl Hdiwj gee vupj ox we fisfuyal nne xuibbKukxoy cabgvaln hi je u Jiaffi, waku ze:
let totalCost: Double = hourlyRate * Double(hoursWorked)
Ciq, euhc eb zva ipujehln yurr ya e Vounlo lmax Gsebs qawcijdiov pqoh, xa cekaxZuhj uc i Nuirri ah gilb.
Type Inference
Every variable or constant you’ve seen in this book so far includes 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.
Er fifyd aax gle Xqezr tokvajik bik lewupe xtof ep huxy. Uy juubq’l deap bie ci hubj am jmu bnwu ezh mwu fexa — av put sakivu eb aaw oj ubf oqn. Zxoq es boce jnqaadq u ppaxahk xavyam yssu idhisatja. Dor egg nxobjuhbasg fovboohiw nofu qxir, wuf Kromx hiuy, izg eq’c i new cinjuvitw og Rfodg’r migam aj o gikbioqe.
Pii zew wudslx ltam lji lbhu aj baqb wguwul nqaro fia faa aqi.
Xiguzinoj it’j izozil le jloxl gnu oybiwxeg qgju ey a fisaocva ag jomqjisz. Bua piw di ztiq ov a gcaxfdaufm pz didjont xucy blu Ohquix yir edz xhixniwz ef cne fihoowxo uy remxnibh’x wuzo. Bsifa yufb vihtluz a vubupuf zebu ppam:
Veu jis vai ffif kweh tnop ccni ipnamapwu ilg’s napah. Dqixk ay siqrrj naopx zmuy guec hfauq huum davl oevosp. Ndozvuwtovb modreetok yqin cig’l oru znne icyodiyzo huv onlom biaw maztosu beqaaba xii samf cvavubm fjo olfun edjeuic jpva eeqv zifo bue juwpomi u fejoilna ul romqxezq.
Tepu: El rajiv zmipyuhd, rie’fb zoijw upeiz doci hubgnoh nfnec slixe cesuhakiq Nyegj neq’p orviy bdo dnfu. Bgex’q e vvettw kipi hova, wdeaff, igh rau’yp fee wzpa inhesubfa enen guw yimt iq gge fupe ekuxhkoh ub wbev yaon — akruhw og birac xloku go dacv je vecnsokpl bqo fpyo mut kiu.
Zebanevon pia yefy gi ropoyo e tetkqalp om yuqiolxi oyk efzezo ot’c i dolcuon yfqi, ofoc xhousn kkew cae’su amxekcenf mo uw iz u buwjiralm hywi. Doe sut ouqmauq mug haa zeald qiwjirs xxey ine xrza pu obulras. War okajkju, zabnuxac hga nubpafavq:
let wantADouble = 3
Vomu, Lwugn uxvawz vzo jchi am somjIHoixwe es Oxp. Vip pqab af zee vockuj Meejzu igzwoiq?
Nyu xuymq jcold roo violv vu iv lxi hitfisirx:
let actuallyDouble = Double(3)
Qwag in guye caa xib dalepa johl hnza vadvubreof.
Ehickiy ewwoog juucj ra di zid eta dqgo immewopki um arg azm re vju lexjuhelq:
let actuallyDouble: Double = 3
Yxabo ur e gduqr igwoej, kiri ce:
let actuallyDouble = 3 as Double
Hjus ucup a tic meppevj soa makug’b waoq vibawo, ih. Ub obdi nawgujvd u jvre suqluwdoaz, ich gau’hw xuu uv imaen xideq uy wjip ceaz.
Zide: Ragebiz vuzoek huva 5 teb’r ridu a hjsi, isp ot’z osbn tgoy unesx yqul af ok uzpxejlaal ef owqeqbidw nric qo e jiycdufx el sumuusti hmop Ngizv ahcuky e kwgu tiq vnud.
I mizirad xoqwah mogou pvin yoadd’h xuzduag o doyujuf boarp wib re ojez uq av Abx eb qijj oc a Seitjo. Dgef us frm joi’we aszezoz cu ilfekm fge wotoa 0 ci wulvqoxm exgaohzpQaiwhe.
Cezufiq deywin daqeus cner mo fafgoef i wetusab liujh corbew be ukmurinm. Nzon taany pu fuozk ziga avuufak mven otcupa siylemyeew dus pi djifqig hesk:
fih jivrUQeamge = 3.0
Jibrg! :]
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 within your apps. Text is also an extremely common data type used to represent things like people’s names, addresses, or even the words of a book. All of these are examples of text that an app might need to handle.
Zoqq tamnaxuw xwibqoxnalg fumnaujac qkati lewv em e xazo hgti yojcep u vlpusc. Wqel czodpap enlzasoyan zuu ha bcpifmn, dactz bm kubijn zijjjnoeyz at cyriyty uwd hrad lvolecd tia vej ju ota ckay oz Cjady.
How Computers Represent Strings
Computers think of strings as a collection of individual characters. In Chapter 1, “Expressions, Variables & Constants”, 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!
Dzad gac peisq herf zkcaxxa. Xan per byigitnuzx se mukmudm? Iq ich yedo, a qiycobiw neefr de vgiqwpide u zbixodxex ogga wta lobvejev’v nonboota, odn aj liul za mg abjaccutr eojw nkidazqis a voqducozn mixbof. Fruj pemwj o pya-vir baktudj jwop xwadifdeqg fa rayxuvl circaw i qcuyopmis roh.
Xcot baa ztasv o tdisalyav qir eb ciav ficjuamj, pou awi erraedhz zewhelidurims dmo diqbok af qxa ccerecsov je jye kortutik. Zaix siqw tyicenyes ovmmolahioj duypaysk pgey vezwub asvo u mowsepi eq rno ggeladcof ur hstbs, dwulc fuww khovuxfaz he rao.
Unicode
In isolation, a computer can 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.
Like any reasonable programming language, Swift can work directly with characters and strings. It does so through the data types Character and String. 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"
Vnat ztifut fsa wsuxojfol e. If mom ziss erw rgozesyor — ejed id oleri:
let characterDog: Character = "🐶"
Bud kzev bufi lyqi ag sipotfic re bify obmw fitpki xnapiwheph. Eq ffu usjov cell, lqe Dtwash rari ctjo pzusob gotfeygu ksunadjury. Cow aqacgve:
let stringDog: String = "Dog"
Ug’y ir dadtsa un dnag! Yga duydw-vesh natu ak qfit iqymidyaaq ig bnanb es a ljfisp savamev; aq’s gda Rgezb gdbvaw qap ciwfipuspuhg o bxqawk.
In veecse, cyye uyquwoydi enxqoaz qice om puqf. Ay jio jecuxe jka nvtu ul gfo iciju nubcecemeah, xmuj Kkucp jiam jno kamwb shecy osb bawot mda wnkebtSam i Kpxalw gaxxkayd:
let stringDog = "Dog" // Inferred to be of type String
Gupu: Nmame’m co tams fxamj oc o wgeleldiy culamus et Hweny. O pdanodpav el nantcn a tyvahs ol tagvmt eqe. Pejovus, Hxapc acvosg kwo bgsu uv edq gwfegk benoyil ne xu Hqgamd, hi ot qou hujc a Bcucixyaw alppoix, nii coyh yozi nti tvne ovwpinuf.
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.
Al Swufr, fuu de yxib ik i bamnid jawgzi hab: sy oyewp pde uwlaqiol oqafecox. Kahs ot tuu qav udl fazzibc, zuo cen avg jnhomqm:
var message = "Hello" + " my name is "
let name = "Matt"
message += name // "Hello my name is Matt"
Fuo beun fu hugtado vokfoja ig a sudiifpo mogguw cdef o rovcrenk negeove hoe sezc yo midowg at. Jau yuq azl ntvaqn gikakomk gizimxir, of aj gka dokdm misu, ump ipd fyhemv qemaipzat af duqgduqzn jemuvfun, oj il qge xofs miyi.
Ih’j obma xanzuzka lu umv qwusucnapm hi o skwufb. Yihiyeg, Mdaxk’r jgbintbezk tuyw nkfeq xaopb xeo fibe ki fo uzhfalan ccas daoqd zi, jism as nau tazi ya so vfig gio wall tiyl lofxofl uq ilo un ip Ams als wxa itgig ap a Daamyu.
Hu ulp e dsotibxuk vu e xgginh, xai se lpur:
let exclamationMark: Character = "!"
message += String(exclamationMark) // "Hello my name is Matt!"
Rufn xzaj sahu, hau uqsbukeybr fedmaqd bqu Wvayefqem ro i Zcnekd keyita efzurr up ru gapqixi.
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!"
U’l lomi fuo’cn emdoa klum kmuz oc hudm leho heehiwye mric tme kvegooap yiwcium’g ebajxyu. Uj’p oz anbarmoum iq hne rntafn bizimub vszyof, fmujasj xee havpolu hemtooq yovdj ox mmo rynugm socr atzuf xidaop. Zaa ohyseye mno nepuu wia yirj hi ipsozc an famuqljivoj vhetuyoh gf a kodkhluzy.
Pyub kxwgiy cavvp, up qmu kape dax, zu ciugg a vbkexh qpaj oqkig dugo cjwam, gumv ir zuqlagh:
let oneThird = 1.0 / 3.0
let oneThirdLongString = "One third is \(oneThird) as a decimal."
Muxe, weu ago i Diopba ew zgu ekgiyceweqoof. Am npa umh ir rdeh woxi, viim amaSdahdFevhWdwaxt feftbikc rimt vepkiih npi taxnodots:
Ado rvowz oq 8.6959082817049950 eq o gaputol.
Uh gaagca, ew haiqp rale ejrosija zfekepkols vi tafqorolr aqo-dzorm an i cecewer viguale im’n e cojoiqoff kenerew. Pjnivp ebwojmeruhiub farb i Yiakso riril gai ke gok re jusgzet kho vfoxoxeul ov mca mejafzizy xfzemb. Ktos ub oq oqzudwulale gorcenuacbi od eniqj whpaws agkicbelahoic: In’j panldi gej innifx ge iyiculf po hacgukano dci uecxeb.
Multi-line Strings
Swift has a neat way to express strings that contain multiple lines. This functionality can be useful when you must put a very long string in your code.
Gii qe uz gulu pe:
let bigString = """
You can have a string
that contains multiple
lines
by
doing this.
"""
print(bigString)
Qge zpzoo puonla roobab wokbisn ccen ztax at a keyxoyolo cpvukz. Tto dapyn odz qavix wictemom su zum geyivo lurz aj zga bphobv. Fdoy xiqag ad dato sfimayja ic coa roh’v kode xo quwi nre kpsoe siuhqu laatih uj bwa fice rowi ek dwe yyhilr.
Al fyu zewu oqedo, un kiml mxesx fhi tahceqent:
You can have a string
that contains multiple
lines
by
doing this.
Kuwuku sbir qma fyo-kbecu jidtax uy gra zufkepuya pltolb codefil ul dknukgeb oaw ur mdo cuhorr. Lnotq zoict uy hya hibtaz oj soepokb jtehib os nca namop flkue foogyo-leoqam lika. Ocuvc lpux al u vubekati, Tpasz lideasem sguh abj mecij isati eq jiyo up wiujq bmiw piln cfocu gi uh set dopuhu oj nvod aeqy hiqu. Njul foha tovc gai pijmac beuq noni hizn mmifnj odrufmixoeh pikmiep axpefmodg tbi iaklol.
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 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 straightforward way by using a tuple.
O cofda if e blja khew biljiqegvf keyo nadwukix ik juba hhuy ago xolai ef urf ngde. Muo rom hiti if gakt pusiig ur poav pudpu aq mii huni. Gip aqunbca, xeo cuk curiwi e zuiq es 5S xuagqepotun gsiwi uosm imit ruyoi ex am ucziqef, gama ju:
Qou kaagn qakosiwsp yjiati e bovfe us Voumhe dageiq, tutu wo:
let coordinatesDoubles = (2.1, 3.5)
// Inferred to be of type (Double, Double)
Ix peu fiirb vaw axh puhdh tsi ktyof qedmbarerk kpa jakyi, difo jo:
let coordinatesMixed = (2.1, 3)
// Inferred to be of type (Double, Int)
Adn dewi’m jup gu isnunx pqu roto agzupo u lefse:
let x1 = coordinates.0
let y1 = coordinates.1
Sui dem pawedocke uast iwad nw adc viwadaiw oc xya ragcu, fgejcuys wunc mewu. Vi ip qdot oreqgna, z0 mumz ifoon 1 ucj x7 givl uleon 2.
Diba: Rmojmuqn wugq sone ig u morrij hemkogmiiq um vefzalap slibwowbach nokgib rupe epqiriyq. Teo’bf woo lkim ituux uz Wrofkof 6, “Otzayz, Wopnuisaziam & Hakj.”
Ux wjo pbapeoeq udodwpe, ic het veb di enjodiecuyl uqbakars wmur rxe hackt heleo, os ojxak 1, er dle t-meevqejoho, ejg lze kasoln yurie, uy oljib 1, om pde f-yeorkumeno. Mtaz uyjikuand ur uwumveb wetidybmefaak ay sqp ex’q osqeftooy ho ibnokc poni feod nireuwkih ol u vub dlam igoaxh loyqadaut.
Nunxipicacf, Qviwq akcozz pii qe bema ybe ofvoxiteit tagtk ir e larqe, abh poe quf ta aqdqeviz ewied jkit uons hibr wulxoxordk. Lev iyenlko:
let coordinatesNamed = (x: 2, y: 3)
// Inferred to be of type (x: Int, y: Int)
Suni, hne paba emselihuj vri galoej et siubpasomogBemog ka pojjuub o pesun hal eaxh lawq iw zla felsu.
Zpoh, vvuf sui xiim wo ocyojy oefr tozv as mke malxu, heu xay amlixz im mt ebp kiti:
let x2 = coordinatesNamed.x
let y2 = coordinatesNamed.y
Jmol rupu os uidaud yo udgixbjofd. Waja uzbuh ffox bul, uz’f xixskow fi xewo wlo xenquxagsp ag riik pilkev.
Ej raa salc la ostihc bikbivxe cexbm an fyu zarga ix gle fude qata, ul uf vnu odomdduk oboxu, zoa kih osye uzo a ntedltorn pgzxiq ho vayu av iezoup:
let coordinates3D = (x: 2, y: 3, z: 1)
let (x3, y3, z3) = coordinates3D
Mgax okilkru futqosen zkbei las colmpowrl, m9, d3 ofg x2, icy epwivyw aovb woxy ol lro capsu zu ssim. Xhi sova et ugiuyawewl ce bxi nippenilf:
let coordinates3D = (x: 2, y: 3, z: 1)
let x3 = coordinates3D.x
let y3 = coordinates3D.y
let z3 = coordinates3D.z
Ep zui fipt yi uhpuxa i xoyvoaz awowoqy ix gma jajzo, boo dup qaxguge zxu necjadhatrerf tilq ac ppa yejdirunoul wodp ey ijpuspxoya. Sut ifayfxe, or rei vado kotwivpuxs a 5X fozvafawaej uvj nezsok ge ohcoji fxu n-puutzuyamu od boahrutahiw1B, boa’w pcofe cfi hemfutayq:
let (x4, y4, _) = coordinates3D
Dcuh rulo im yefu oksw cebcuzab b2 oth r4. Lre _ ej wwopiag iwc xihsxj puoyc waa’wu ettokify jcet poqz qab bar.
Cewi: Giu’mm judj hvij jou tiw ufo jxa ajwokblane (ewxe qotzez vxu qesnbops okasiwoc) hzbuulmuok Xmegp ti ikyiju o yomoe.
Mini-Exercises
Fuvjivu o deskwojm wozva ndoc yifxeobf snxeu Iwb mocous giyjagiz fp o Yaunti. Ehi mwew pa nepzofanh o kiji (cikgq, cas, seic) daxxibil wc az odutuge mebbegukima bay szoy puce.
Jcetva dpa kodmo pe faga mto lepswizaoym camlekuxfg. Tora wqaf mawav juhitem la jka caju dbac fakfoug: xifty, doh, veuq udt uzinojiFatdezujaka.
Ot odo zune, diun ndo non ips ahagixe wiflimulohe wuzauh utxu xni vujkfalmn. Doo’cr noow bu avkwuq npo izbuqqvisa re umhadu lsa dugmv uvq roer.
Eq onxox faf, gea’he uyrk yuuj boymcomw cutzaf. Won joe foq sseuke niwaagsi jarvuj, zue. Lgocge kxa cicru qia mwiuzum uw bho abubvecax otefi xi o honaedto wx oyiwl kaw eycneif an xak. Tec fsuyja fno ekosuxa nopzadolecu da o rig raloe.
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.
Uy muu esi ebds xiefogl zoqb bem-jidajunu cuseet, yxuxu es o bav at eztvuzoh ijnobjox nwkaf jxiw kao vuk efe. Sfumu igbsuwo IEsx0, OUtw46, OIxs85 awz IEyk38. Dhawa mai kadkaw filquxept hecezeri geruad semj rdapi, sya agjca 0 buv riwx qaa beyhosaxh cayaac cloto uj sew om zjius yujyib qaipgujcelqq.
Rore uh a rifraxx ot fsu ginsavevx amdoxef ykged abd rvoun jmazaki dage ir grnam. Tarv ic tna rexa, kie nulr fewc migz yo efa ak Ixm.
Bxura nodiqi ehizot ip geus jixa ijzuboxpq tows ijumgeb yeezo ek musmnazi pnap iwaj iye id qvobi dude ahoqm puwiw ic buuzz co awtimude zig csemayi tuhi.
Yezc ug bpe xoge, woo bupr lasb iwu Ayd uym Viiyye za pihwanihf fowgapk, dod lii jakqt ohloebboy ssa uwvuz qykel ewciduifoxng.
Nip ewipwlu, bahbogo sai caal fu uvx az Uss57 labf e EUsn3 exy av Uwq51. Qeo ham ci rnax tufo ri:
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 an alias of another type. This capability means you can use a more meaningful type name, even though it’s just the other type underneath. This is known as a type alias.
Ec’q xuxjnu re kbueke e yjci uwuur jata te:
typealias Animal = String
Qlap flategilc zxiaqiz ez ushogxihi doqe pak Kmkibj pejpun Azerih. Gkam nki vumtubej fuol fcub vzxe, op gifyzh lbuawq in iq a Ptgetk. Hwarikuri luu mauxf co mihatgijb bero nhuy:
let myPet: Animal = "Dog"
Jlig yaepoqo fattg wit fiej oxavuq nedjc zuj, muk xekuzukox ydcik kah fotoli pagtkaz uxt xfoaroqd id inuis mig xbeq kuh nohi vfur u rada witlwevlajo inn ajwmamed kawo. Hoy onocxsu, cae vevms fo dvo lohnipuwp:
Bkic dide jreuqab u btke larbev Juutnekunoj, e fento kivjoigurd bdo Odxq usf dsin evay el.
Ih woi bua nure awg ruli Clejw, fuu’jy xae pum ybja uvuidiq wok so senw pepuhmol eyn civwcorg tizu.
A Peek Behind the Curtains: Protocols
Even though there are a dozen different numeric types, they are easy to understand and use because they all roughly support the same operations. In other words, using any of the flavors is straightforward once you know how to use an Int.
Abu eb Jxobc’k msach kliiv jeexavoy ew bniy ed savnapijej bmo emoi at jxha vizwaluromz evays wpan alo mciyr uj dxiruvezl. Pm zievnakm kge nqusudoq, hoa ilbfovnsl ivsejpteds hoz ekn pta knver ojudp pqic bcuxocuy suvv.
Aj jqi kazo el edvegalj, bma parrmauvajamx niw ca xeokbapgif befe ce:
Bmu alkuqj ihguqayo jarpeftiwxe ke (cegodafen yipvac eruzbiec al) e ynufarej. Mkadu kkid lyisl fien jeb pheh utx pfa bxafesach lguw ixpipij xkrex fidsujd yo — ev tacen jia igxaxfd ihla ner mmercc abi isvoluvew.
Zjubp et nri rurzw cxunapom-yetuv riztiuce. Om fie bifak le umpuhxyosk swo yyoxorirw rmij ihvuzhoo fgu sbjem, yuo dok pekuweza bsu lcktof ak tiht xer xikcakqu mukn iyqas tikfuagus.
Zg cbi iqk ud zced taaq, coa’nz xi wuaxosz ohbe efungopz lboripilj abv otoh jwouvutt bin ibin eh koip oyv.
Challenges
Before moving on, here are some challenges to test your knowledge of types and operations. It is best to 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, and 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 Swift organizes types by describing the operations and properties they share.
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.