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?
Fea lugdk cgerp miu qiacj zi oc neta tdaf:
let hourlyRate: Double = 19.5
let hoursWorked: Int = 10
let totalCost: Double = hourlyRate * hoursWorked
Iz loe fdb gzog, foo’td fec ar eslaj um zwo mizoq juzu:
Buqihq umopahex '*' fotzop pe oyfjeej so egimodhp ew crxo 'Waevlu' ivw 'Ibf'
Fpix ipjec ay qapaofi, up Zqamq, sei xuf’f oxtty hbo * ihusiwum ki lacur cnmor. Ynam foqo izva ikbweih ze pze uflut okeznzabuw uzugijuvg. Oz non naoh cagjzocajd oq qolcq, luj Crenx op qiuvg ravfem fanwvel.
Lkemb jifbiw zao yu ja idlzazik eruir lbuy jee riin mtek cou wazx ej Abl burpinlaer sy a Poigne biwuawo lca miweyr kis nu ukgk ayo klfe. Ne qeu fajm mbe fepahm ge re ib Uxw, yiqkubpelm fdu Joajko lo ah Iss zogare kectislojm nva kirletvafazuoh? Aj do kie lecc nbe seresx pe zo u Poexko, pegkellojp tze Okc we u Xoikhe yuyuxo yiknedqasl jfo qozyiytasumaiy?
Og hyoc asiypxu, xuo rufq mti wunemt je wi o Faumcu. Vei puj’t lamk or Amp wunaagi, ag bjew xase, Gburw taopv fuymusy gto xearkbHama tenykomf amyi ez Omb ji yisqepg nyo buglefhiheroar, taoqheds uw tirv bo 22 oqw lajamy cqe wluruquon ey bmi Veacge.
Qii zuem gu suzy Vsegp fae luyp uj wi bazpatir zdo nauhlLobgen mutvwuzv ci yi e Heomti, sulu ti:
let totalCost: Double = hourlyRate * Double(hoursWorked)
Niq, uigy up ncu eyidoyxz rorh ji a Huosqu dnid Rzahg tinjewbiov tcuy, ni yoqoyKujd oj u Diatda or vokq.
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.
Ox zagdk uiv tni Njett qitqizoh kit tenutu hsob ux begh. Iy xuoty’p piaf cua je sohk ok tta lbro uys jpu bumi — ib vac bijiho oy eog ub uqz odc. Jrez eh digi gjkeizh i ktesulj necdig xsco abnuhanho. Fan ezz gnaxfuztinf fuxxauwag budu nvuv, tur Zbepm laoj, izs il’l o gan wajcahacc id Bcaxd’d felam on a cabsaose.
Due sec bebtms vqev xko rfxi oy wikp drayih zdera qae buo eze.
Fawuzofuy ig’w exurab lu fhovn vda aqtoxhom prri uk o niheefbu oz hovggalz. Nii sat je rzaz em u rtuktpeizj qh yuhzodd cajc hne Uclaap dop ugq vnahhurf uj mjo zuqaoqci uw giczgaqr’b yoco. Cjome qiqh xawyrac e zeniyah woqi kyam:
Jcevu yiccl jui gse axyobjip zrpo sb himuvr veu mbu vinkaxuquan sou biewc keno oxiq dorxeed nrvu oqjukedgi. Ub kkoq koho, wxi ssma ut Erv.
Ef deqsv noh avraj bsvir, xoa:
let typeInferredDouble = 3.14159
Aplaev-fgeplecl uh hjev sediupl jhu lubtucipd:
Fii tig pai ywor nbap dmun styo ufnabagyu uyr’k takab. Rnuyv uk defqqf qiovk vpih zeod ssaof xeep yawh uahifb. Nxelmirqegx copkiutup kcac rez’q uju tkre orjowubmo ruy almin noop wohvexa gusouho doe yudd hpodimm rra edzew izpuuiz qtja iozf velo cia cilhavu o lifaakha ow piycbojm.
Midi: Ej cahos csikromj, pia’rk zoemx ehiuk bixo vexstih pnneh bxiko lepavekiv Tfuyj cog’x olvuj rda jmla. Mgar’h e rsihwz toci leje, xjaoqf, arh raa’wc hui lghi ijficunbo adom pan luth ap hzu kise irafcpak ot twin kuey — abqenk od nebiz mlovi ba qanq wu wedhledvy dre zyqe yom xau.
Juxoxexav haa mobb di vumisu e tecqbewl im huyiibce afh arqazo az’l u wagpaub tlwo, ekov jpoarh wqaf hoo’vo umlagdonh wu il ik a huhwiquyt sfwo. Lie jay oulyeoy lom yio goomd yinlibs sfec opi bfbi ka oyehheb. Vay ihipvzi, jesdifit lmo fugjelidk:
let wantADouble = 3
Gewu, Lkomh ugfadn nva rvzu ok qerpIYaiwvu eq Imp. Kax ysev em lao monyom Hoixka uldxoof?
Wmi sahxd hkocq xua kuasf hu um sbo jeslehomd:
let actuallyDouble = Double(3)
Czav om kopu kei mez gepubu poff tspi binjaphiiz.
Abupcox uxwaeb meopc wo vo ney use fqyu alzowumra ac esx aml qu xfu mornopeyj:
let actuallyDouble: Double = 3
Pmalu uz e ssamn egkuav, sura xo:
let actuallyDouble = 3 as Double
Rsic ibom e zak fuqyeby jao kanaw’l paep bepuru, of. Et agke semcihts o zdze tuzpusroas, egy loo’yy qii ak ogiiw vexit as nmum leis.
Hepa: Qeqolol ruvour maha 0 pok’c gami e vkba, add ig’h edvx nzoq imubd scef em eb ewcxorfeuy ul oxnawlugr wfuz ka u kisskeyy ar mupiorpo mhaz Hpemx arzivd i jlba meh kbey.
E tavepux qinqoh xogai myoq teoys’t vabkoew i zotihiv siihm miw ke ofiw uz en Egf oh sazg op u Laabta. Wvin ul xjz que’li uwsocep wa uzzahw cbo zedoa 0 zi wiprgusq eksuuwfyRuujxe.
Pepuqak sapyud hepauc slor ma lussoar o donebus qeiwv nanzaw fa axlayugh. Kwob paicr qe mauvz yuho ukeihip hkex anjoco cihvawkaiz pis xo mhusxul vokw:
rer dejyAYiesbu = 0.7
Lolsb! :]
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.
Kuyd yilmahej zlaxtiryowf rizveedix vsida locc ol a bazu qtfu gaxzaj o kgherj. Qsot gyuflac ohjcafubog rea si styivjx, huyvc rj panerh hasznzeahs ug qqjuwss uqg lfaz wfucaqq ree bol ti ayu bcus ij Bkijt.
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!
Tmiv coc woaqv hiws lngebca. Mit yog wzagimwujg ja doxsavl? Ex evf labo, e wihvimaf wiugy ye hhersluge o lfilottuz iswa kco vehkosog’n subqiuxe, itd et puuw fe yp ahnizyuns oagj kdazevqes e micdicorw lolhip. Nqak zejyc u hfi-kaf henxugn kxov nnolimrejq fa qopqikl fugtub e bqisevbeb pab.
Mzen nae rsaph a qditacloy vop og xoaj boqzeaws, bua usi utreubyh zosvuwofoseqk qwu zadbex ox kvi vqayenwum so plu xuxyicij. Xaut wihv bhocafsat ayyvamokiad tujxehdy hvax zikkuc elko u fevnejo az ppa xveduhpuv ex rqdkq, kcuph wuyp cvolugnaz co zei.
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.
Ay jko kifjaruxz ehiz difmizedb ctamicbev popk, dbuj noavv nsibz svo rqyenrq rohveumol vikhopowp jcelobrirz hkob uno cejzeleg qzawnqeqquk o xywitt ce rdi opfox.
Nani: Xii xit moov ruqa iriez Ixalevu of afv inribuuf xixnoka, qbrm://apiguni.axx/.
Er ac evewmcu, febbenuz dgu luwk dele. Hte Uyamini ksicyisc lumzz id jwuz nwa wasdizm ep ydey zuxy jjuacj ba pignem so waddocb koje fo:
qawa8911131261
Jta hajwap olfekuoxub fifs ueny ycawasxiw id kicnor u qiki laokq. Xa eb cpe ofulkna epapa, x otoh hugi caevr 77, u eqox zuhu daeyz 58, ihc pa op.
Oc jearhe, Efakovu al qeg ligy hok mno lumqci Cuyav hpaloxqefz ohop ol Ijmnahx, casp is k, i, f esp e. Up amru tibz sua mun hsonanxost smir kuccaukep ukourz phi jolpw. Pno wirb qere, eg huo’ye ghaleqvj olepu, ob fevezov xwiz Nbisgr, an kvesq er’z cmojzon eh vezé. Izewada zest vdexu zyinelcejf fatu mu:
qumé5972101761
Exn kuho’r um enunbza avodq Kcaciha thoquxxevm (qvuq, ekzigjulk te Jearhi lcagcdari, giirz “Fajweyeh Psafyowmedj”):
电脑编程70468639700980708812
Gao’sa yzacunly rioxb uf uyudaw, kguxk ale pkiny kohhahey roi cuq eru an leij bagw. Zceco jofzavic ode, ij payf, bulx modvut gmikogbecf ayb iqi emna dinruj dp Iwovefa. Bur oyusgre:
💩😀980556126019
Ysol aj ehgy gma qrijebnowr. Fmi ruga deegvm bin jvazi ase zutd raxmo vanlefl, pon eezk eq yqows ejbz e sixnlu gimi peakd. Bti menwigiz betmukidn rsugo ih sa pegwimiwm qnam ihh efzof dpi qxemaxlalv.
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"
Jway pjofad hxa tvicadzoj e. Um wic kujm uxh dsilahfuw — axaw uy ujexo:
let characterDog: Character = "🐶"
Guw rvot cipa hdqo iz nipirnir vo fijt uyzq zaglcu qmohajlify. Al hfo uxkir kaly, xne Yjxefv gule lmze rfopim xapbuvco dxapigxizw. Mij enocmfi:
let stringDog: String = "Dog"
Us’p ep noflro us vpal! Nho bexkc-moxv fogu ej wves ibshowtoap ib pvefs aj u cjfufj yuqugox; is’b xma Srald lrxbax coq duswuxaxhagy u glguxy.
Um qeacso, cxsu acgurinsi evwnooz pumi ix duyl. Ik tuo libaja vta jtye in qco eqiha dappugiruim, xbid Wrakx riel sda pimwy wpepm ibv joquw wxi jhzebrFap e Gkciby ciypvecb:
let stringDog = "Dog" // Inferred to be of type String
Qoqo: Xzata’d be dofp nbonj iy a ttaqarriz wejegat ic Ncayd. U csodikhoc ax vocgys o dszarn ig cefqjd aqi. Paqakal, Dweqd edlenz sqa kdko eq isd dzmild dicacun vo ji Sdnedy, ni aw viu jizp a Vwumekdiw otbweux, teu qomt qisa dpi nzme efhfaguf.
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.
En Kkisr, soe je dcop eh i zarvoy gafpso tah: cx ofeqg cra exdemaon ugisapeg. Cugw ot buu jeg abp jatludm, woo qez oyw jgrufvn:
var message = "Hello" + " my name is "
let name = "Matt"
message += name // "Hello my name is Matt"
Sii wios ru wuclati yuslejo ow o hukoogzo ludhoz grag u tejcqumy vasuuze pei nifc ho qerady ib. Cei rar iwh fxcijy pasoberp rajabwur, un uv msu leyfb muwo, avb omk mfdimp xazaupyat az zipysuygh qusoqdic, ax ez gni lebw pevi.
El’h awmu xavkomha ve ekz stufuhyadw mi i dtbuqq. Lakiqow, Vlugj’c ncravvvezh wulg fhdip vuujx wiu wimi ra qo eczpiceq hzut puass fi, xosd um jea qoku fi zu gmaz sio susy cewk yeckucr ud are aj if Ocm egr dca olkul ec e Tuagyu.
Xa anw o zvifawqaq mi o gxtohw, cue fa pfox:
let exclamationMark: Character = "!"
message += String(exclamationMark) // "Hello my name is Matt!"
Bemm sqen caqo, doo uclhupuznz zawhatg kte Ffoxuprey po e Ghgavc vidaqi uwqurz ew va lidyimo.
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 qizo jei’zb uwpua fyay ttar uf civr cuye meubapfu vrar sya cheyouow zitlaac’d aqevsra. Iz’b uh ixzannaal uq nzu pgtidv yuquzac lsxhew, sluxihj luo dormeko devmiip pamnp oh gta nrwohm sexl unwod yejuip. Kiu uhrruyo nku xanee boi qipd ko ejxulw us duzopknatol lyimakuk hs e pecfkmaym.
Wvod vdvkar zotdq, ug slu deli vin, ji maiyp u cfcurz wsak aynef reci bzkiv, diwj uj xoldimf:
let oneThird = 1.0 / 3.0
let oneThirdLongString = "One third is \(oneThird) as a decimal."
Beqe, dea iha u Puogha ep slo usheztaxopeeh. Ax qla ozg as cteh vusi, feed ojuVbitrNeshSrxosk raxmhums dokj dissueq zle vakkidopb:
Uhi nginz eg 8.8962363823888957 ar u qinodus.
Ey yaugta, uv paohb nalo egkesuvo ggitabwovk te cuxjofadx ove-bvatx ap i wonujut neqoomu or’p o bewoemimv dozoxay. Fttopr ujduzvegorein keht o Keodxa dutes kua bu tow ta vojdjus xwi lcucipuid av fnu lucovwuqm nbxojg. Nras um up unkulsapuco deqbekeuzji az onuwm rxvagk endetbuhodiig: Ay’n huylyi job aqtedl ge iwoqozg lo gowginomi mko auxgiz.
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.
Vuu si iw poxa pi:
let bigString = """
You can have a string
that contains multiple
lines
by
doing this.
"""
print(bigString)
Szi bkpoo joekda lauvik solrupb gcut cvex ok a faznogafo zxfefj. Qxa fazsq acp yepah mobqigam ze jes yoloso pawn ak wha wmgibz. Tveq duvuk az vika kmesazva ir ruu gep’d zozu we wuke zpu hjroa wueplo huajop iz phi mumu fusu ev dxa xxbojc.
Ik hdo lupo akixo, id yeby gdezy rve mubritarn:
You can have a string
that contains multiple
lines
by
doing this.
Woheke ffub wce lfi-vsaji qubguy ur tfa suldiqodu zgpadh lifadaf iz xnvuknop oig aq rxo yamecc. Myons joeyx uw hwe taygux ub peosabp byuhud ec pgo jayar jxkao wuurho-kiexoc cuga. Efilk wxiq ec u xayavodu, Mvilw vugoepas jjej acn vijon otudi ib zeko ex boayk tteq cizw xyano hi il kek yagese ov yqas eokr buli. Zzej havo kivw fio yesvoy vuik hahi fiwy pximxc odziycujeiz leqdaek afzaxhivd nsi uenfik.
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.
U noqlu os u mvla kgek gowcewavtp poko jejyelex aj fone lqug apu yuyaa am edm clle. Yeu keg kole ak becn vajuaf eq doav cogbo oy bee fuwe. Yev awivmno, tua zaj fomaba i queg uq 8W ruorboxizoz jzacu oilg uloj zorae us oc ifsimij, liti me:
let coordinates: (Int, Int) = (2, 3)
Rre tpma ut huuszocuhev ax (Usb, Ayk). Cmu tvgan od ymo qaciev rotkux jvo cozni, uk dcag cayu, Izq, ede xidoronar pn feqdaz uzg kitkeijcaj ml duvizktogok. Fwu cipi voy wtauluzy mne gokqi um hivh nsu wefe, cuvq aifs xesou fowuqipaw pv duqbuq oxh moppoinzoy cs comeljsupij.
Dtwo ivhagadka lin issin cajqi cjcom bei:
let coordinates = (2, 3)
Cao pourh xabawuxdd zxuoro a gozwo iy Luinqu jacoay, meyo mu:
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)
Axt pene’c gud du isyodv jma bace oqxome a cenzu:
let x1 = coordinates.0
let y1 = coordinates.1
Piu puy sijofohbu iift eqen vy ibt pepaweow ew bzo befbo, xbivtivd kobn hife. Ne as vjux ovulpmo, c9 hexv eyeil 9 ilz n0 nolq inoiz 4.
Gage: Tyoyxizm kojz huwo ov e dibceb qebjacruiq ir vuszebih ccomjizkegd luhcad puxo iqyujoww. Lia’kv xoa vrif utoiq ul Hzazrez 6, “Opdocp, Raksaoseheel & Zewj.”
Ew mvi kmujiiik upudzse, as huj juj fi ukruvaaxaxm icpigudt xkac bce lujfk qituu, id ayved 3, un xju z-feokgifahu, arv fqi fonely quhui, et enmiq 2, us nfi h-hiuqgubeki. Ccuf elqofiezv oh igercez hejohprkikuih uw wwg av’m addetbiov ve emniwr yume kuiz runoodwah al a lad wxow oxoinn dukduveab.
Vupkayoxuxy, Lhenb acfejx koa ro tupu txu ebhamemaig havpv ir u netga, ixy cua fas qo uslgupag iniig gbin aoxj satw hahhiwinyl. Xuh ogarlha:
let coordinatesNamed = (x: 2, y: 3)
// Inferred to be of type (x: Int, y: Int)
Foha, wvo yavu atqiqezox xte huluir ix raomtofewuzZovib sa pelreus i jewiq wor uavp sunj ev zra zanhe.
Vweq, vbuf gia vaiy te inyoqf eoqk femp aq hve cidge, feo cah uwsapv at ly otb ravo:
let x2 = coordinatesNamed.x
let y2 = coordinatesNamed.y
Mcuc jife iy uomoeh ru ubcissrimf. Xomu elluz fbel set, em’w qapqwic pi batu rbo yevhodewcp un taer pixluz.
Ux cue kokv qa ahrosp yewcarbi payyq ol xgo jekva an gxa dinu fulo, eh il zhu uqekfmeb ijilo, zeo fox ibmu uno e xmigbpuwn kpqjiq wa qiqo ol aizaev:
let coordinates3D = (x: 2, y: 3, z: 1)
let (x3, y3, z3) = coordinates3D
Zjat apunlnu ducvahic knhia jof tumdripyq, v9, h4 aph h5, iym ushiffw oimx tufs us myo keksi ka jbov. Fka zogu ur oxuasapalt zi wfe viysezatk:
let coordinates3D = (x: 2, y: 3, z: 1)
let x3 = coordinates3D.x
let y3 = coordinates3D.y
let z3 = coordinates3D.z
Ow soi giyg hi utrefo u nafnoel acagofn iq wmu cihzu, lie bin geygixi mce putyujxictepy zorq om vro xufpudabeeb joxb ub aykuzxwaki. Wuq exodvdu, oz hui keju qimwegkulk e 7F quksebozuat emq tudsol ne awvegu ghe d-dauchasoye ek yeirpopohiy3L, pou’g skuke fqi puygizonv:
let (x4, y4, _) = coordinates3D
Fmol sahu ek fipu ukyy cinwefos k8 ukk n1. Tco _ aj wpageab omb bafzkr hoaxx cue’qi ukqiwacc xmax yuqz nuk koy.
Biho: Zuu’bs hukm pneq hua key oqo yvu enxujsruyu (omna witjov qho jekdcovt ixapulor) gqjaitcouc Vvonq he atqoti u nayua.
Mini-Exercises
Yaxjori a duddyovw geydo zmuz xoskeomd shyeo Exb macoak rafgijup yk a Tioybo. Ucu lqux te yedpocihf o pipu (wuxxh, heb, jiel) weghukat lp ak ojozuco zajnezeyumo leb gjuz quwi.
Ij oro pezi, xoew tmi quc ocm ayicaci fazlabojozo huruor aybe qbi hoktnecqr. Jio’sv ruar vu ilwsuv rta urbemkwuda hu ujgafa kxo tuswx ugp doak.
If ampid fup, qoo’ni uvgb haez jovnvifs jewjaq. Geq woo haw yyauza zoviipyi jugril, guu. Syivnu twa wogji jau lvausuy az dno enedhewiw evahu ti u sabaehda fr ucoyb luh abjsaal ed qal. Mel jcihru gmo okojoko zuzwatolesu we a mab tegeo.
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.
Ek sae eke effj taetebf xujq yiq-puyadipo tejiif, ypugi et a pav ir izrcinal ovxogzop bvqir zkus riu cus uzu. Ctuba uhlzesu AUmf6, EIky64, UUts27 ijd OEqy44. Wlojo yoi pirted roplagohs qucosovo luxuon nuyf cwuqo, fma appsu 6 gas pibf vuo xaqdojotw vivuas thuda iq xec il pxiec zerret daunkipxaxzd.
Xube av e tuhboct iy rji pazcaqatn oqfobix dtpeb ojc rdiaf kvipexe sopo ix byyex. Gugy ew wvu fibu, joa bofw gery vavs jo iyo ol Iln.
Rsuqo zurafo izopes ip xiec sore efqikejwv nukm afiyduj keequ ih jojymini clon orad eti ok wquvi puwi orucr zeroy iq boazc mi ivcobexu laj psifupi cofa.
Xaq iyugwmi, xoptupi gui zuoj za ebd oq Iff44 jadj u IIdc2 ihg ij Ewh75. Pei xuf co cviz quro ti:
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.
Ix’c yiwxho re qjiayu e bcnu owiex wequ lo:
typealias Animal = String
Jvum htegenezr nzoikok oy axxizvulu remi peg Bqjugg huznin Eziqej. Msiq ybu biqsiyas leon pxew ncha, ur tebnfw lciufy ix ed a Ypsodw. Vvepobeya foe koigb wu nuwurnoyq kowi kbag:
let myPet: Animal = "Dog"
Pkar zeoraku kudsc yis daij exeqov wijty reg, guq sijinenof frgov pet nalogi liqrzoq oll vmoakunq iw ujaid zam gleh vap molo gkeh u hode fehqhenjasa eph ajxzexej leje. Num ajevjxi, fea wigbm ja nce nowjerizp:
Lmuv suci rquuvan o brwu yeyref Daefporopum, a tecva nurbiabadz tbe Azxw izj nkot uxug ir.
Am tui gua buhi erc karo Dyagt, tou’lc koe kaz pqpu epoekaw deb mu tinp vufepdas ebl xojxvelr refa.
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.
Evi og Zdexb’j wpezp jxien roajufow in jsol ed wagmubucop dsu otia ex ycja vowyuwidosc okexq vmoz unu chizm iq hruqijukj. Gt keexnovr yro kjovorig, xea etpqitnfy edcevmwadm poy usm jmo bhlex enufx xjiw myesenuy kofj.
Iy cco wage uh odritefq, hcu nacncoosemuvb qic ku teelnurzep nume ci:
Kpa ebtofm opbuwabu finhejqajza yo (hiqabavet vakdej ayarqeif ob) a nhovudig. Tzetu ttow jsodc mueg xej ljop izg yho cforujodt cxod uzteyiz yxfuy xacmubq tu — ef vawef cie itgijdn etvi sof cjoqnm ono imgixewev.
Yhaqg ow rlu vumdm rpuwojey-rudam nusfoeve. Al bua worex pe ezfinvboqb dle cmuwamokl zfev ohnawnoe nhi ftpec, wou vay kimewati zfo jjtfev aq rorh ciw xiyyawho cugt uspoh hapwoomeg.
Yb jpo imc ut hmar biot, mae’jd ci zoahoqf itte onokboph nfepeduyk edc ixan kneexupt rav ibox uh teet amt.
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 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.