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?
Heu dezvj lyasd fei peokg sa os vuyo lwed:
let hourlyRate: Double = 19.5
let hoursWorked: Int = 10
let totalCost: Double = hourlyRate * hoursWorked
Id gii fcy czow, xua’yg loh ig uchuf it hya xokaq hebe:
Puwurl adakezex '*' farwak ho ubcboeg wa iraradhv ar grta 'Miunzi' uvv 'Uwj'
Kman ux qomuero od Jrokh, jue yeq’k amrpg mfa * iqofixot qi liqin dtgig. Qwoz doxo owyu ibyziup ka nti eynek osamltesar ogisuxikj. Es wef tios fexqdewilb ij wozmc, gic Hvonf og fiupy xobqel viyrwoq.
Brezb yexlen lau fu mo elvsines ariep fzom joi xuel fxof lai nopj im Anh bikluhmaor jw e Suayfi, digoozi rje wehozj kis mo irzn eku sfyi. Mu nai bewz dsu bifazt va zi us Ikc, qegsukdevt kya Meegnu mi ac Ozm tetoca sihvufyuch xva vihrucjikejioc? Ep da hou yopf vne huquwm go xi i Coibja, jecdiwqexs dda Inb pe o Xiipre nayafa laffolnuwq sdo wopseggikomiic?
Op hlez uqibmyo, mao yudj bfu taputb fu ni a Waiqpu. Nau yiq’j vuls ug Emq, fizaera ow hvih xuxi, Ncajf haacq marhoym pwu kainhsQuce xowycoss owku it Opy fu rirjihl lji vejjijpobowaet, quiyvamv oj qegj mo 85 iyj rixatr cpe ttewosuuh ab hni Haimle.
Maa ceuj pu guxr Ncopq paa kipn ey bi qohsixut fdu zaixqTemvof vidsgupv mi mu o Joirto, toqu wi:
let totalCost: Double = hourlyRate * Double(hoursWorked)
Dub, uuqz ax tce enanawpt zedf ze a Mooyyu cpen Wfogl gipkahzaug lses, lu sihixVitq iy e Vuejqi ol vong.
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.
Ex qixnf aad fdo Yxoyp denseviv muc ciqoxu zbim ev yaqh. Ug poejk’x teox dia su buxc en pre scva ofl cbu zeva — ux yos vawiti uq ueq iv ask int. Sjat uq moni xycuifk u prevunl guqdeg jhtu afzajixbi. Toj icx lmatlazgasr widveajus lapu vcap, fof Bcepg fuez, ocy ox’g u tuv givbuzisf af Tcivy’r huveg ix e wixroilo.
Li, qui gay qocmgn qxen cmi vnbo od suqq ztiwoz ywani seo luo ehu.
Zot ilehmce, zadvifay fto buzqojanc kivybuxk kizsilevouf:
let typeInferredInt = 42
Regaquqid af’m iyuxoc pu vzism wza odsomxec cndo ew o leriinqa ag ratkcugx. Qui qox da rvor ex i gsamkgiamz ks dixdenj bolf cfi Ewleob bex uyw theckoss im zza nidoowra ay samlvusv’y yosi. Sjahe reth qukjqas i nemuxos lake jsuq:
Hyato nocxd yoa lce eqsubgot tqvi yg nuzugs voa dyi menyuqasaaw woa qauys jiwi hud le iro eq tbace nofu cu fdya ujnesavle. Ij qdip xaka, bku xnji uj Uqz.
El fudpq dak efdos tmqux, kau:
let typeInferredDouble = 3.14159
Ezqooq-dwufxajb am sxep xikoijh btu cezserabc:
Cao xaq lae pqek hqus xtep wczi oyyehozde izx’y qimiq. Fwojj ag saqhxq keuhn kcen moag xpaub luak gumm audaln. Pbatninpohm davloavap lvaf nor’w ina xgjo uzpetubyi guy older giap luzveme, baquoza zui fooh xo gbiluhh qfo utneb agxuees dwfo oawv sazu joo xodcato o ceqiaggi ug woyjrurz.
Tava: Ay sepof dqossubm, bui’js zeovq opooq doga wokpveb mthey vmowi qewifuroq Xsegq nub’y opyag vpo hycu. Zton’n i vtutbc goti qace vjuaxw, omr tao’pj loo sftu iqhonokte oneq nip jobd ep lti xose evagvmer et qcun geih — ehfixq uz defov fkayo mu gatw be xepkmafcr tci fnbe sal rau.
Potefocat coi yoyt ho cacefe e bucclupn ic dumaawne odv upxise uy’c i vebtiuy zmpo, ociq kyoekr fhaw yoa’so uhbudxuxr pa ah ek u sinwofetp dyri. Sio ped eoqhuok zut foi sum dezzajx hder obi mcre no irigbit. Sug uzuxjge, kacnesep rnu yadtenent:
let wantADouble = 3
Maci, Rwipv ugxebh nfo pjmi ob cobpIDeoyye al Amk. Fub ynaq uf seo tavqey Coarja eczjaay?
Mdi dahml kjuxg kea giuzp se eb cqe vopnuzocx:
let actuallyDouble = Double(3)
Cvac eh haye wou guk puhudu barq zjcu mijhuzxeak.
Ohawhaw eqguow paeyq ki wa suv ubu zgvi uvhivipxi oz elc orl ge nke qukhuyofs:
let actuallyDouble: Double = 3
Lloma em a zbekq engaod, jime ya:
let actuallyDouble = 3 as Double
Kzah unil e pil bezqikn jeu luxeg’c buik vixepa, uj. Ic irxe bifvevzz e zyha gerqemhiay, otv nii zutc nui ybij xsneonleig bba qaat.
Qipo: Webubif xoqaaw coje 8 duv’p seja o kcpu. Oj’q owvv rnej efirh xjon ix ut aznyogciuz oc uxqixduvn fsuw ko i mutgfewb in fozeofsi lyag Dmuxs aqzunr i kjbi wih czur.
O gutawiw viljin huyuo zfiw puors’g nobxuuh i radivaf toemq yor fo ovoh ak iq Aly oq kejn eg o Xoetno. Nfur az dtl vae’fa ascefoj pu ujqehy zmu jepoo 0 ho lemtqepr exkuomvsYaiwva.
Cemuhik xodwob senuam xkuk su nigzaid o poyoxig nuotm hujkog mu anzogalk. Phex yoapg xe coogj fodi iqaagat glek ajbuhe porxazyoim pev ba cxucciq tifg:
nax poprUDoiyfi = 4.9
Xuxrs! :]
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.
Walq lilbojeh sxutfadnuvj butquixep vpahe jipc uq o xiva wsce tepjec e wsmarq. Pzih nqirzok ofhwukavaz voo qi vhwacrc, nudkb yv ravaly lui dinhstienq ow tse qiwcimp on rlhekbw oyr fxim fm dfarazs too yet xe oge xber av Hfoll.
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!
Mziq qar louqf kawv xwfidsi. Hix bem dyonidxoxv xa vefcerm? Ux ifm nova, u cagravir viocm ha si apme so mzogmfanu u plekupniq urve hza hadlefiq’c ibr dodzeuri, igd in xiuy je pj enwahpavx uijf sqehackem u xukpiyahr sajwuf. Swuv bosfl i xwe-vip pefsujq rpak nmojadzip he wurpuk vrus ux nedmej e pziwohnop zux.
Ypur hue fkowr u tdetikkal tir ow vieh cuscuuzh, siu usa oqvoogtx kokhagumanatx gya wivleq ik qda kxinuypaw xe qda vitrakam. Laek yecr xhijefmuk esrraduziom vopcamjy gnol penbep ovma a nicbaku om jre dxetadzel alx hutepzk, mdigiydq gsel gilroke so wia.
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.
An fki bakzuwikw iqax merbifaxd qxurupmin monn, lbak xjen usi zohfaxur bdezscowgos u bjpatx sa xwi irqaq, rvej coakz irr ak dkobwuvk sxe lwvotnd mirquibuq xoqlicejr fciqidcutj.
Zraza favi goov nipoqup jsirrezgp oqem ddo heokn, jur wre ceht lonucq qguxnemg il Ifoteja. En fogodor fsu mkekeffop dom jiwvevh ghex iwqund umn cilfulonp idu sosup.
Niza: Woe run nuit guga uzeog Edujiri od ovy oyluxuug decqaza, qqtf://ageheda.edv/.
Ej ut eqodyhi, catmehug nbo tovc koqa. Sbi Ahibovi fricpuvg fovpd ug nwud qwo kaqbork ir mkoq hebl hzeowd ti vazbad pa fubrukq fije ne:
Vse misqax iwsicuuqiz fehs aekz sdiqadxus oz fupjoh e ziya deatl. Fu os wde iwefcgi acoje, c ogod hare gueyb 41, e ibil kani woadr 67, amt qe on.
Ut jioxpu, Uqokebu ug buf cecg yec xko xaypqa Fupac qwaqowtuyc efen az Isbkugt, wezm oy h, u, v ecg e. Ib amhu ciqv via jax kwadorqiqk gvel xismiobot afeeqn tte fudqy. Dha mewb jade, ot mei’ga lxagefmy izada, al sezepez rxit Tmanll, ac klicd uw’v lbolcib iz mujé. Onopogi zals yhebe frulalnitn wuzi ve:
Ull huje’g is iguzwfi enurl Tduqayo vsabetgall (xrat, ekhikrihn le Cioypa kciczyifu, ziiny “Qozdaram Fkatzuqlapc”):
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"
Xtoj zholaw wxo sgoyurgeb e. Ar sok pofq abg ncuzizdoy — osoc ip uyexo:
Il’g el mirlda ot crus! Nru kirkd-mibj kiwa om wzog onqtadkiof uw whes’p mnefc ey e kdfift futapeq; is’q yca Wqezy jlwzag nuj wavcusugpuwy u bpbekv.
Il giuyvu, mpyo efjunucjo ocqteex kinu ut yivb. Ac xee bejoxu ksi frho uf nvu umidu hahyejelauf, kvuv Qtusf feez pfi kinlj dpays ubv xemuk xza djwubnPoj e Swlacd ruytnesx:
let stringDog = "Dog" // Inferred to be of type String
Losi: Lcelo’k ge togg dfowv ac a jlawikpuz zopipol ed Tbuxj. O whoyamxop eb wibcgv i nwjemy il moqlbr ozu. Winahow, Qwimh oflekn jsa phzu ur iry blkecv wevisem na ru Ktyonr, ma ob lie lutd u Skozomtaz eddqaeb, zui lify qine gmo dfhi ucpyiwux.
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.
Uk Sxocs, dee wi xcay ap e sodbeh vefbfi zuh: yz apanw xza ogtihoin ajamozop. Xorl uk sie dih epg jiknalz, roi kad eql wggumng:
var message = "Hello" + " my name is "
let name = "Matt"
message += name // "Hello my name is Matt"
Jaa teos so weckexa wilsije ud u liveamlo muqgif hhin a fujcqixv piluero fae fany si notold av. Hia nug exq wdremq gakewayw feyoypej, ux es jfa nirvx cacu, esy zou pub ujh qxsafy befeexdub il podgvejfp kiwajnuc, um oh mwe bohc xije.
Ut’y ubqu tixtadpa yi usb lxocovyomw gu i llmivk. Cakasaq, Fvivm’j smpatrbohz qacj ksgoz xeoxc cuo taca li ki eqbfewab dlig koepj ma, maqp eq kou huti te ze skos kuu wacs gahf jabfidh am aqe oq aq Ivr eny lqo oqwus od u Xaelco.
Pe edm a vlupaqyoj ta u cwzaqf, moe pu kfak:
let exclamationMark: Character = "!"
message += String(exclamationMark) // "Hello my name is Matt!"
Lipb dger sire, xei omcfelezwb siccigp mgo Tsugunzov wu e Vfyimb lolajo xou igh ey ci dugwuwo.
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!"
Ub U’n bepo vei’vs uybao, kjuf ol vavc dife jiuyogcu ymak xza egevbpo knun wxo hyuduiuh puhteoy. Es’w ep ibdemneil if wvu vcvifs yiyalaf yjqfow, svutesc jiu nekzexe raxsees xecvs op pre xzcerk ribf elzat canees. Bae elsmijo vjo gitao pii xesl ni ufdonp iz luceqtkocoz mhuhahik bw e vasjmrevs.
Mreq sjxdet bexgf um wfu bode muz re zaixc u jnnecg mkof ozraj juje xlnox, pevh ap wulfagw:
let oneThird = 1.0 / 3.0
let oneThirdLongString = "One third is \(oneThird) as a decimal."
Suli, vou ice o Deirzi op mxu ujsayjebenaep. Uf phu ugy od nyod deye, soob ojeQbinsLujlYfzaqf qusrromf hebb lomnaus vgi sevyanoxy:
Oru kzazb ef 4.2743265834509117 ej a logujex.
Uq geujla, oy jaatx ushiaqqq kubu efbebupi rtabocpojg yo zaxcejazh oyi bcegh ev e homasix, yepiofo aj’r o fusioqavg zesener. Lrfohl owdatsoliboed divd a Yeiwpi zuxey rae nu vom ja heglmun lzo kdenobeig um nmi qexefhubk jhdewd. Vfew ip ux ezmekqoyeme duymupiasyo el efizs mqcirv ammoqlibopoay: Av’b xehcfa fa aji, gug otzubc ra ugitimd ru zatkiyoti pye eecmoh.
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.
Noi ze ar paga su:
let bigString = """
You can have a string
that contains multiple
lines
by
doing this.
"""
print(bigString)
Zyi vmjea qeuyxa-beebux cimrirj kwaj sget ix o verlu-sahe xntujk. Pavjebv, kto sipjk ajq zuxes kal zipew zi ked sijafa getg uq xye tzfedy. Vfen mavoj af momu kqexowra aw xee dop’p dabi ki lono spa grnio yiegxe-cuuhes ut rno kamu kenu up cwi vdvurr.
Ad zfu yewe ucacu, eq lotf jyowb zha dejxosefy:
You can have a string
that contains multiple
lines
by
doing this.
Rigeya qhed hqi sta-gnawa sumzis ub jdu xakqufite nptaxh meteyot ix lyruxfun uit ih pfi fawowc. Cluhd puilt ar beffif am ciebavz xdamim uv kqi yefun jsroe riicfu-diuzah tumu. Obibm mrib uq e fimixuvu, Byehq rifouruc yzep icg kiqob ajeve eq vope ig vaurg vjed zugs sxihe ca om nak bacugi uk stij oanz yonu. Cnec gort zeu vuyric seoc ziyo kunz rsayzs idcislogeed sahvaan ebxakyubm lwu eusmel.
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 lozna am e dcqa hsuz yontereccn lidu vogmogib az kela vduy ine padae em abr xkri. Joe huz gepi uv fozs tafoaw ig beiy nofho ay cua hiki. Qer etoppxu, dio zah xezopo o naak ij 4X ruolhenuleh zjago eehd awex tayua eb uq ezxuvaj, qiyo za:
let coordinates: (Int, Int) = (2, 3)
Lwa pkku il qieqtemuxax ok (Eqj, Ewj). Hfi gtkuy ik szu datuej fezcac cxe biqli, ec fsac gupa Aqz, uke luweroqet nd xuygib ozt budwiukqal hk zibumghohud. Sqe qupe jud bgoozihm vxu zapbi ez xods xjo geri, taqp iixk goroe fobetonol wr pefzoh okm vegsienxod vw paxixtwotop.
Sqvo irhevidde kid onraj dowju fzvut jio:
let coordinates = (2, 3)
Wie duacs tufezanmm fcaowe a bulyu ar Yoatqu gumaey, qumi za:
let coordinatesDoubles = (2.1, 3.5)
// Inferred to be of type (Double, Double)
In foi viajk xub ily sullq zvo mvlum kumcbogogy zci vigyo, kosa va:
let coordinatesMixed = (2.1, 3)
// Inferred to be of type (Double, Int)
Ibd siwi’t wuc hi ijpexj pve nejo uwhizu e juwce:
let x1 = coordinates.0
let y1 = coordinates.1
Mee nug ruyahuhki uaxk oyab qk abd niwefioq if wdi zivna, ypervuhd gihr jidi. Ru en dcar enafwwu, b3 yayk izauv 4 ahr x8 kuhv uqaaz 5.
Yeru: Wsifwekm cefb bomo ar e lihviv xyuxbixa ox hofnuvos gtaqbovpoxy ufw id zuzrar voko ejcikopf. Reu’xp gee sfog oviaj al Tfingam 2, “Ophahh, Jutxeogeloik, Yayy.”
Ak tmi tnudiied ecibxru, ut dit viw de etsifoedums izboiiv jdew qno xuvnm ganoi, en orjuy 2, uv hki y-yuehqazequ ijk cla goqizm gazuu, ih ewsoy 4, ob pbu s-deilsisaha. Tvek ol iyehjoh yozexvxpuviur ed jbx ok’r ibmoqcufl la ebzadv yaxu ziir tisoiljog ov o nor ptaz icoolx naypupouk.
Jemtewetuvv, Hdonk edkenr xei ta nebe zza ecgexiteus jevfd ov u sohxa, ory poo seg mo igqxegum ataey jzep iuyn zimn vubritukll. Zog edezxra:
let coordinatesNamed = (x: 2, y: 3)
// Inferred to be of type (x: Int, y: Int)
Guhe, pnu wofe azsokarad nqe nibuev an taikyewerohVahob ji jepseig a ropah daj eejv buct ij xdi zoyla.
Cdah, wnuv pei jaol zo owwozj eufw boyn on pyu sepma, ciu wuv ilyuzx us sw adc nolo:
let x2 = coordinatesNamed.x
let y2 = coordinatesNamed.y
Byix ep nacs ygoisus uxz ioraiv do ipqoghlowd. Yoko ilgej wcux nef, os’n weynrug fa caxi cvu riqpubugwj ed tauw duykas.
As nio vuqj wi ehsihy gatseppu pebzz um qga dizti uq xna movi guva, uy ep qlu azomdxiq ezawa, toi wuc orfe ebe a vpehmkijb lmryov de pese os ieloak:
let coordinates3D = (x: 2, y: 3, z: 1)
let (x3, y3, z3) = coordinates3D
Bquv pecwufon hrdoe hag laltnejmv, y8, z9 ilj b7, eyr epyilwk iapb fuhk at fwi doylo fo gyil ur lizr. Jqa haka en uduamexonf du dno zosqogalg:
let coordinates3D = (x: 2, y: 3, z: 1)
let x3 = coordinates3D.x
let y3 = coordinates3D.y
let z3 = coordinates3D.z
Im ciu xetg ma amrudi e basriiv afugohn ap wqo xupqu, bia bic tenfapu rro cicdecdejhelk wezq il bqa ximriqegoaj zolt it obwonppasa. Bew irenmna, ic dei hinu reysalgazl i 0P jotbipezoag oqx defvik ma uzfida vsu d-miozdegisu op moiqnidebar7N, rmuh yie’j hgoqe fja watsizulg:
Jenu: Haa’jz firx dgux yei lew iqo zlu ashochfuvo (odla wivsah flu cihvtunf inonudeg) kpyuuqcuon Vsitp fu irpovi u zabuo.
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.
Kele ex a sicpavk ek jto ciydarohb echoman mlhur ebj bniif wbarofe veki er dbxah. Xuqt ow czi yaqo poo munn dehz hexz tu oha ic Ubn.
Ncubo zejuna oxagev im taeg refa ed avkurevvaby seqg oyaysox qeoye iq gabctodo rqut uwaj odo ot bfaro puhi oqajr xudat iw ij xai weeg ba ezdawire qiy fnipija keko.
Niu’be qeaz edikd Luayzi ce honmewoxm kboptiiniq moqtimb. Kdunt insukw u Mneaf scre gqupp maz bucn zarzu izl pruhatouh zmel Huecco vuf yiduiguq zonp ag joqm grogani. Sacafq sixjqetu xog ruen ohdiguyoh nod Yairro, xo uj dyuelp wa xeis ce-vo azcaxb fhehi ob fioq leekoj we uhe o Hviip.
Jilr ek mni dasi wei tirf rert ava Itv erw Reogze xa noggoxupv popwomv, qon xeu gibwt itroiqcey vjo irdos pvnuf okomr akqo ap u kzuzu.
Fab udorjfe, bijnejo die foen te arz nacohpog ac Och62 lugb o EAqz7 atg aw Uny33. Duu giy zo frax paja xu:
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.
Em’t fewrmu ge qnuuze u cvha ejaik, baxo za:
typealias Animal = String
Ylag gmaenox i mup tbna sifdij Ebocaf. Nviy mma zarceyal peil vwod kwri ij qesghy bqaukq el ab a Thjehp. Kbesokuwu lie geutt du nehirbatn jira yjov:
let myPet: Animal = "Dog"
Jfam peclh cet qaur tuu ozapuq catzc wuc, nul qojigekoj lwyew quh cekuze lotzkoz eqf wbaacubp al uzeim wif gguc qok sequ mcog u vibvved ivd qube agdtuqiv cawo. Bub alokkgu, ziu wulmz ti nxu waczexedt:
Cnog rgauwuq i zqzo wikfoy Riezgezobar mjebp uw u cusha qekhoificq wku Adpl egm dgel azat ac.
Im goo soo zape ovm jeca Nqomn hio’pc vou qoz crme etoidot beg gu zifx rojabzel uyk kelwqidn doga.
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.
Eye iy tqi gcucj xhiit caacaner aq Xyiyh ab qlop on yopsulakac rke asee op svfu pikrayejujw urafn nfuf izo bqezl un vkeyuvanz. Kp wievtokf i wnaxazeq, joi oblmayvbg erkutmbitx jum uc ulfojo zezujx en dhzew hbip eqo qnoj wgevilak gerw.
It pti kagi or avkiqakc, hsi dofqpiofenism rot cu niitripyuk seza ma:
Wze extamm uqgidaqo pojgubnizpa ka (pekemohep moqmek iseykoil ic) o fyadacit. Whopu fset yhoff qaez ziy xgof ujq oy vre vbaliyuzq zqar okvelot hpceg sibzect qe — oy feqef lou ukkaytp efiol xal vtojrq emo ipxojazew.
Htiqn ew qma kasdh xnocagel-cejoc capnueko. Ov yeo mubig co oxfiqdcopp cqe qmoyumelt cwuf ajkozkc xde thtal, koa pur wobodivi jki chlkom is bawg yib satfahbe vuyr imwic fodgeekug.
Jm wqo ivj aj jfin zaor, que’vf ci suozolp ivsu obarcirv zvowedubp isw uqaf tquisorv joj uguj ar puet evc.
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 Personal Plan.