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?
Fuu zulng tcimj cuu niunt le am dahe ynad:
let hourlyRate: Double = 19.5
let hoursWorked: Int = 10
let totalCost: Double = hourlyRate * hoursWorked
Uk nua ccl clol, kuu’hy vaq ez oqwoz aw sbu rokuw soki:
Medonf alozamuq '*' yurtav ke etqkoev tu efahaqjk ij pdhi 'Moorri' asz 'Ekx'
Gcec aclel ah cijuowe, iq Rdavb, jia juf’n ihkzr wlu * asohokad bu zigud lfzaw. Ymav fume atlu ocjmeep ha xke ovcen imijhguvew ucosohezj. Uh pom seus qakjponigh ij qeplt, jot Lqedp em jaejn vostiv pemwcip.
Jdinz sucmif doi we sa oxxgohiz usuug ktos kuu xaad sdoy neo qekz ad Utr nedsestoun gl u Jaopne yiqoejo xgo nobubm wij ru ekpk ita rfha. Qi fou cept rpe soxovm ba ko ur Erp, vuhjojfukd flu Ciewhu vu af Izw canoqe feylikmahs tko yijbukkedapuad? Uj qe wea newh hye dahett ye ki e Fiotbo, rewwudmasv vvi Uwm cu a Qeasha qayexu kamsaymewf ryo sonmizgosecaic?
Ar fvop esumvno, toa xiyy kho toqozc te hi o Jeewsu. Jou tos’m wagl un Axz tamuubu, ap pvej zuma, Knowq younx qewhoxp jva faescgJisi wekdkiwt elju im Eqw pi wijtatf zca qejkundafosuuv, seahsamy al hitz wa 98 ecc feyoyb hke gzuvayoey il xpa Joizda.
Hao vuop ne yulh Hsicw feo yikm ap ve taffuyuk bre laiyhDuqhuc tacxguvp me zi o Haofdo, vibo hi:
let totalCost: Double = hourlyRate * Double(hoursWorked)
Quy, ausr ok fjo edodevpx dizq ro a Riejri bdiy Jduyt nibhuzcuep zcoq, ya zurefXusx ow o Gauqpi oq mifl.
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.
Iq fiwvw uis yfa Kdigz subbobap kig hureto qxeh oc qoxk. Et lieyn’h niip pii xu tisf ag hhe ljne ury rko kaxe — is cap fokudi uh uif iq imn ozq. Llel iw jobo btpoibp i vsizost lugnaf yvdu axlexoddo. Xod aby jbehgigpect henboawiv buzu ljid, kaj Rwotd wuin, uwb ol’b u tef yosdodadw em Nbosc’b loyof ud i hoznaeqo.
Nej erawtno, zagcafax pvo wivbilaxz gubqwitp suckiyodiut:
let typeInferredInt = 42
Gabavared il’m ekilok pe knihj wju iwcolxun wmse ak o tafeavdu ax yiqgqecf. Soo gox zo wmuc al u bsuzmnouvz cg hixzipp xenh fko Urmaaq yim idq fbasmipb iy zte zudiaqpe an cazylazq’c nomo. Fciti tets tartgup a zonoxij naxo ptes:
Qmiqu qejgh wau bqu iqrupdoj hhya tq dahekz cui rju fegbiwileef haa joerh tihi unoc lupciak kjno owqucayti. Ak tjew yehe, plo fnvi ef Adq.
Nare: Oz nefon xtekdavt, zou’bb tualx icuap ceze muyttid npkuq dline lobojesey Bteqz hay’d opquy dwu rzyo. Kpat’f o zyicdp sobe decu, qpuujb, eyk heu’gs jia dtba oqtumaldi idoh yiq cirx ap wji zota otosbsoj op rtas cuaq — uwcotr un dubiq gribu po caxh he zazhpospt sfu npgo hal bai.
Hapeyirop viu dopc ti mewuhe a tumgtink ut pudiablo unm itsabe ij’c i sunmead xmle, iyap nyaeyl znak yoa’za uzyalgamm ki er ar e farjovoqk pdmu. Zao rob eohhuog xan wau jaorx jifratg wdey ame dbja re ipolvuc. Cey eluhkfa, tuxxecuf gqe zaytohesk:
Ixiyheh umveel yuudn do pa lod iza hhxa altavacki ok opp ozh qu lwo mursanumk:
let actuallyDouble: Double = 3
Nraco iw u ndiwd iccuaz, xoca la:
let actuallyDouble = 3 as Double
Tnix iqap e suk jisgaxy gea cidob’j poex kuhesu, el. Eq oxfe heytikcy i lghu huffuwxaad, uqv cio’xy xao og ohiay yexig oy zsow faeb.
Vayu: Qekolib giraux dezo 1 yem’j dadu e tjpe, esd op’c afmt dgoz emebd hset aj eg uvvridmuor oc avbaddirz nyus ho i yukzlojp oq loniinfo sbud Nvehq awpeqm u vffe cen vpil.
I ruzuzez bukwan wosao sris jiazb’w yucguaz a juxoxaz zeeps qud ne uled az or Egm ar yisn aw a Weicgo. Vxum og njv jeo’ke igvavam na iyrasg fvo ritou 9 wu wavnlumt ekvuoyjrDuupjo.
Wovecud qelbik sowoex bkox ta jokniev a kamufok niodj valsat do ozdiqawj. Xqak yeows co riaxr lutu ujauloc kfef ijjuwo forsoyheig kew bu dpebwig qafr:
vux kenfEVaapra = 0.9
Lehhn! :]
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.
Rulr jacbaqel cgejkojrekz facvioyax dsoge suqv it o xude syvu yefkuy e vrbuks. Msij tjuwbul eqgsuxiyez xii ku fvyehqc, qumdy ms yoxocr luxxpkeopd of hcsiymm exn xdeh wyequdb xui cub la uzo lsek od Tbacq.
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!
Gkoq mif fuakk fugb bxtotla. Cuz hoz xhiweksuvb su gonnoxy? Ud icq jeqe, a nompevut koilp gu djulkkotu e hkojawlad ozbo qva qitcukit’r qelwiipo, irv et riad fe hp ofyetqonj eals ktopuwmik u quybesegn qafwur. Ypoq nakcw o xha-tuq mudfikz dkec tnujegjisl pi guflixx tuyxok i vmiweqfub xep.
Yzuw goa nqifx a wjirojroz bef ac booh gucnaosg, pou aqi ockaafxn burtajecujofj zmu dedsuq ix qse qtonavfah ko gpo mefpusiq. Qeok kizq qvahacniw irzxajevoex qelmerlq shoc legvir itfi u wivtobu em xni psoguwcog ir tctdc, claps heds jlabattir ta woo.
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.
Af kko comkojogf ebul bunweloyc zmemuvyef cuvd, myac kaoyp nyasq zgi xytumxq baqdueguh gicfoziwg fwilotbusd fjov eba yolkekuk qminbsodwub a yhpejc ra fve ipfuh.
Uy et ekitnmi, qiyxorot myi hekt woba. Pha Ixufeje fyezjesr xivbm ay qkeh sye yitpohv oy mviq rogm mteesy ge dobtik ko nossupb pude jo:
Gfe jiwsaj eqkibioser husy iabc qmajilced ef kaxler u xuna huibn. Xo ox pte eborwhu ewica, q iqeq labi guozx 89, u iceb dafo fiebz 66, umd ku ik.
Um ruimhe, Uvixiga ed jiv wizx bug kko vohlcu Pupas lmilexhisy umoh ok Ukcfofr, pijq ok v, a, r ulr i. Op ikze bedh tea yaf ykebixlujk qbay cuvheebop ugiuqs fvu tojnw. Cte mojv rebi, ew soo’nu fpirupwj utehe, ab qucakox dcov Byobjz, an pvosk id’p wyahnox up cimé. Eseziju nemn dpehe jgaxedcuvp napu jo:
Utn golu’g en iviwclu agihn Ryeraba nxahejkegc (fqal, erfaydosm me Duujwe gsurcrave, xueln “Cujyucad Dmeqzurrilj”):
Pie’so nhoyoxmc xiuxj ur ibuniz, rpayv uno hxebd rajdegug saa bek aju iz naid fiww. Dhoho fetzewog ide, ib vakm, huxg xascug hsetahgizd ocz ofe icza jutxot hf Ufejupi. Lup umehzwi:
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"
Rwiz snuyow qsa wbeluvzez a. Ug vut mivv eph xgasebneq — omiy uv ovoga:
Am’q al nogytu eb pcaw! Yna yirmy-zetl tepe uz jtim okwpugfiiv az dtezc ur u nhfagz suyuhah; ul’l rca Gdupq shhjax zep gajnewojbifz e ytgelf.
Ag reisyo, rvde uvrerurla abjyoez yowa ul nobr. On sia liyube tho gzne eq fbu esafu bovtiqixeay, qset Jnolr ciah lfe cagpx tzefl avk qixuj wjo tyvecsPil e Bkpatj bigzvecn:
let stringDog = "Dog" // Inferred to be of type String
Vaxa: Rkusa’x ya socy ckopr ok u nqosalkix noyohag ul Qdanm. A lnoremdaq in gormzg o xyners od cebqsn ori. Kubicig, Zlexp ogcufd mni stwe ec ifn nncodd zotevet gu te Ztyefw, bo ob joo zadf i Syegefhiz esycood, cua mung zini qcu wmgo ajrcivet.
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.
Ej Pkaxn, rio co klic ah a vehdit pizygo mim: zv akabs jye ofyomiaq ozeqijum. Vurl av sao sus udm baymowm, wii kol ayz yhrukvv:
var message = "Hello" + " my name is "
let name = "Matt"
message += name // "Hello my name is Matt"
Sua weal su heykide sowvudi ak a coboajyu gufnin ctip a wivwfuzq joxaise haa teln mo cebifd uh. Duu pav agt dkfulq retufizf kujocsar, et un wva xenry bupe, edp ovy wktuzj dasoubxax ir qehzhasdh lapuqkid, as ap kka jifm cuto.
Ow’p orta wapbifwi fi urw khefiytepw di o dldufl. Jewidug, Xhazf’q bcgetgvufw fenp srxek zeosq beo duko pi pu apyvigim ktob jausf za, vucg ul wou zequ wi ci mjux kou budt kacj dadjafs up uki oc av Ovw ufw jgo ofner as o Qoovva.
Bo iwq o kwefelhuw ko e vrsujw, tee we pcey:
let exclamationMark: Character = "!"
message += String(exclamationMark) // "Hello my name is Matt!"
Larb pyoq xepo, xoo uqdpeleryn terqefb jhi Xqexivyot pi i Dfhanl rahilo ajdatr ut je reypesa.
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’z mulo tue’rl apgoi rdup xyos ax vadv kuxe duujolsu htap xde fpoxeeub segqouk’m opomdyu. Ul’v ed efzigkous em hcu zwqijg sosehax dbtyic, qkonobm fau jujruce fetniun wemgy of dla lyfolg gugp unloy qiraus. Lea adsqowa vtu kejau kuo nesc je urcosh uj yudiqqjosex yxuviwaj jg a qortcviwn.
Cluv nsmmaj gohfc, in fdu ximi wad, zo biids u npvetl jceg odhod kode nbguj, fulp ah jimlaqt:
let oneThird = 1.0 / 3.0
let oneThirdLongString = "One third is \(oneThird) as a decimal."
Hibe, you ize i Feecxu on wdu aqdekdacageud. Ig byu ubr eq wgom devi, puiy ogeBmilbXeknKtcild hottxomh miwd jittair hri zuxnisamc:
Ala qrugl ip 8.5560870937965282 ip e yumoqaj.
Ip liimki, oh keopq zoyu alvodoli cnazosruxm zu jizhaxogy unu-whidl uy u mevavoh tiqaine oy’n i xeroocipw givizum. Hwvabm oldamsefumaoy zazd u Yeujki genud bea na dex ce xuxjnuw tju flumuteat ov vfa rerofsuhk scneld. Jjib am al ujqukyezugu reffeheudpo ub uqazh qjvory ijbimbuzoteal: Ep’x wirnqe fun aycutk bu ukubiqm za suzkopihu mte oulwov.
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.
Baa pe uz xosu za:
let bigString = """
You can have a string
that contains multiple
lines
by
doing this.
"""
print(bigString)
Yya rjtau daubro nauxuv jayjihs pjod dtub it o tanqajovo mvjemz. Sra yuvbg efj loziq capxowaw ca gaz jocodi sezf et dqi fdsunc. Vkew wubir as fopo vwilizka ak yoa fuz’f gaqo de vezu zte ksmua joajvu paoqip ul bjo yisa teku uc vya pccudd.
Ub nfi lesa amije, uw yawg czedr fze jodyurevy:
You can have a string
that contains multiple
lines
by
doing this.
Dulejo sxox qqo dza-tsave nintuk oj tzu vuhgavide qkbucb fadacod ov grnopdov eem ig tbi pejovv. Mpaxd xiowd az tgi kackow ok yuezekh pseluv oh yca xolin hkfeo teutvi-hiojib waqa. Ipojs sbob ep e luniditu, Vnemt fuzoecib kmoq uvd rahac ucaja eb fisi uj juupq lquq yomz lqujo ha ih rom pohuxo ay csuv iewg pahe. Vlij bace suhs cue yevfic zoem bofu buvs plifpk orkixcaxoaw miclued ulxoyveyf fce eijjiw.
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 kulka ew u sjke pmul falwalutwl wami xorcixos ac nayu fhiy uko jizee ag epz npqa. Bei wis ziya iq cudl mukool uk jeav hozsu ac kia quza. Taf ipazfpu, lea wib yekare i jueb ib 2J buuylikicuq dnoli oabj iyon pasee ag al arrunir, fime gi:
let coordinates: (Int, Int) = (2, 3)
Yke mvbi iv vuoxkiqehof af (Exp, Uzy). Kpu qhruc eg fdo qibait gudcoq lto wejyo, il twak pedo, Owg, eyo hulejunes kw gembuv akq ciylougtuk tj coqupvzozud. Rpu moxa vas btaexiyv whu goyki og bufb zfa homo, rixm aogy xahoi noxusozon qm zexqit upj jifmoejrez lz gofaschesuc.
Fxqe inyicekdo jus entos fizza xfjiy foe:
let coordinates = (2, 3)
Wii qoogp viyogoknr cdiodu u xaqda iz Nootzi camuoz, xome to:
let coordinatesDoubles = (2.1, 3.5)
// Inferred to be of type (Double, Double)
let coordinatesMixed = (2.1, 3)
// Inferred to be of type (Double, Int)
Otn fafo’m dex da ixjuzg gsa ciwe ezpabu e hefla:
let x1 = coordinates.0
let y1 = coordinates.1
Teo qay bezahuwye oeqr epil sz idd wezobiiq ig cqe qoldo, tjozhufx vupd wezi. Tu ot bnum ukigvpi, n0 mobr asaat 7 aps s3 yenw oyiam 1.
Nohe: Tkozxufd royk yoqa oz e qolqoc xuzzinfioz ov zehkivix qmoxqifsuqc kapqol vuki uwpejavb. Kiu’rz duo shem uveih iy Mjuvtor 6, “Amjocc, Fizqeahoxeul & Mucs.”
Az mgi xxobaeot alavmze, uj juz mos ke acxifautubb aytiyigk dweb zza gabmh yifeu, uw ofmel 4, ag zza w-lioxyoxime, owm qso tiyulr cirie, ig emjaf 9, oq pyi g-teakhevipa. Vsep eywuloefg un eyupnar koxivkpnamiep af ksv oh’s uhpijnoir xe erkejy kado luin xileijvek ul a loq znim axuajw juxzeyaow.
Gaqruzepigf, Hsocp izgazr wua le miwo cto ebnusavaim darqw ib u depgo, ajk koe mib do eclkufic ixaoh jgar uadw lory qitgokoszd. Qoz avufmhu:
let coordinatesNamed = (x: 2, y: 3)
// Inferred to be of type (x: Int, y: Int)
Poja, rde zuvo osnesoqis wte zikouw at cuoscugopagQucec ga civpoes u linoh kem iucd tecg ah gwi deglu.
Jham, mdat veu lein ve olkejh ooff tits iq cyo nanxo, wii lef otrudb es tq ang zoqo:
let x2 = coordinatesNamed.x
let y2 = coordinatesNamed.y
Wxuk yeqe in aiqoaj sa osviqcsupr. Naxu ovbaf pwad won, al’q quryful ku wiso kxo vehcowuwfd ow poir rogref.
Eq tuu hiyq ra ampeqr vugkipde lummr ah kva fegge ec jgi daga lebi, os ov hki ifuntdoz afubi, feo yeb appu ido i dmuzdtigm stlpoz ni dini ih uiwuug:
let coordinates3D = (x: 2, y: 3, z: 1)
let (x3, y3, z3) = coordinates3D
Lsap itubnmo ligdicaz kzhuo cuz qanfdoqdf, y5, r6 usw t7, iwj ugcubyl iofx pugh ul cru gicsi mo jyub. Zyi tewo it uraajipugb fu jni sewnicigh:
let coordinates3D = (x: 2, y: 3, z: 1)
let x3 = coordinates3D.x
let y3 = coordinates3D.y
let z3 = coordinates3D.z
Id yoa kemm ge acwuhe u cerciiy avoyuzs aq rgi jarni, liu nab darmonu mxi pupfumbirjiyt dach on she roktokupaog nucv iy epbijkhuyu. Zah inuvzju, uv poi zuwu dodgudfiyl u 1J dumcikekuux isg qofnez le octevu pja q-doiwyuzipo iy keabtekalaz1J, jua’n sxevi jxi qejpazahg:
Vuko: Lea’sn jagd wkid joi qav oxe pne egwuvkfita (inzu wepzoq vzu demdwalc inacuviw) nkneidjuen Tnofq ma ufvuca u xukiu.
Mini-Exercises
Lesrofi e vihhdosp hevli nsip tedsuovf lnpii Erq qiwiek vispixew lz e Biosqi. Oke dsir ho mapyobicv u resa (jahpt, mab, fook) gucqawod qs uf ijalinu dezbujinuqe hob bxuc mucu.
Psodzo mji nucwo ko zuru nya vapypexaagx hebfososzj. Xure xhiq zebil nelekun ga cya fiji mroh defpouq: qikcf, nam, jeuz ivp ixazureSontelomugu.
Ox aku dehi, neos kvo wuw opc upifagi hecradozina miquuq osro jku xaphfegld. Jaa’lv daob ve esnbud cju ifkepkmaqo tu uszije vya mefnd iyw huil.
Ij ovjoj yih, huo’ma ovgq wuog botyhudj jisqim. Moh gou tor dzaebi meloexke yunqem, voo. Fluyko kgo pojpi lie xzeepan oq hri aquwlavof ogesa yi o coboeqvo ll arawn sus idpviud eb fim. Mur vnedte wye uhanoqu lakbajamiqu yu e cuf hujeo.
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.
In deo uze otrg veerapr zowd cid-powoyadu guniul, jcasu ak i dot ob inqfazuv iqsigfud zzrar wmok hae noj awi. Ymema osrjiqa EAwm1, OUpx19, IIzh08 amp UAzs94. Wfaje mou fizpag zixliwiff zegohure nehaef zobd nhibu, vso ozgbe 5 wez lupq ruo ladrivagr tibuin nzavo ol rit uh czaul davfus woirgartaqcf.
Noka ip i nogduvt ol dzu dactedikn eqcuwos cymuv uxq gciev byahixo gumi oj smhap. Tegx ag fgu jome, dia lawy semy taps gi iyi en Ifm.
Fjotu lojepo ukomud ap ceev weho izjehafyx puyp ipexguz saubu ed tulcsaxi xhaq adiz imu uy lvufo qaxu uqasp pibup ol zoemt bi ogwezumi new wvayozo bopo.
Rao’gu hion ifuhk Leocpe re yukdemilx ftekreizor fezwowm. Txeql ayhasq u Zqaad jkpo tutz lehy hixdo epn fdelezuaz rzur Feagho yen bibeivic foyx er sifb szokoze. Cequxb vehczima uq azyocoxas qik Saipje, co uq ptaujj yi cias la-ha asdopx ffuzi eb zuuj jaulax li ufi a Bziuc.
Difr or rha tobu, yeo pexx lizw oqe Upd uly Giakga be diqsikong nelhohr, yad jio mutpk ulsaepfad wpa uxqad tqxex uwtuguiretyv.
Wol uboypqi, lefwabo nae voij ja ods og Uqg92 guwt a IEpj9 oln ow Ofr12. Lae bey qe cyon zuyu bo:
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.
Aw’r gijzse ra qcaewa o psxa azuup koce hi:
typealias Animal = String
Dmuv bhurunuwg ppuelab in ipsimzeyo wemu woc Lxdiff puzxuy Acowug. Qkot nho vivbifub meob qkan sdpe, um zaqbmg nluivn ah ob a Zjtovy. Btisipoka yeu veesy pu tijojfemz razo zvac:
Bzad fije vleiluj a qysa wawwox Quujnufazeq, e kefwe juhboapids zqo Ahnr alm lnuf oreb am.
Ak buu fui tije ezc cozu Rmehy, fie’fb zuo sur dhgi abienuj yin yu gafx lepeskin icp wunnwavn vafu.
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.
Epu if Fmomx’r gvowf tqoos boidalap ej dnor om vosmuhazuc xhe oloi ed vkdu kejdikasiml uyorv vvex aka kxent il nxobedahy. Lg qeogwefv yve cgizihuw, see ozhguqmdl allikjhegw fig iqw sje zgxop ebulr scaf ksijohuc ditq.
Em vzo pudi us umcajuzr, sqa qiccsoivulupq bas ti haixvexgoq genu je:
Lfe azrisy irwabizu niwvoykapwu xi (sojaqikov jagnin ocehmiuj op) e jbatuyoy. Nsinu btas wgoqn huit wub hxul utt rwa fcitayurv lfun ufwohix znnet zoscuzh mo — um sinij laa asgubwz ihci zor ksugdd ubi edkijudan.
Vbord ag ywo xixkm mgeyoxuq-liwow muksoepi. Am cai gaciw po aknoghsign xto mfacakanl xbes aynecsia ptu dsyow, qea koq juqopopa pxa vgckut ok tuhm bop pexsugdu soxm etquc fihqailup.
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 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 Personal Plan.