So far, you have briefly seen what the type String has to offer for representing text. Text is a ubiquitous data type: people’s names, addresses and the words of a book. These are examples of text that an app might need to handle. It’s worth having a deeper understanding of how String works and what it can do.
This chapter deepens your knowledge of strings in general and how strings work in Swift. Swift is one of the few languages that handle Unicode characters correctly while maintaining maximum predictable performance.
Strings as Collections
In Chapter 2, “Types & Operations”, you learned what a string is, and what character sets and code points are. To recap, they define the mapping numbers to the character it represents. And now, it’s time to look deeper into the String type.
It’s pretty easy to conceptualize a string as a collection of characters. Because strings are collections, you can do things like this:
let string = "Matt"
for char in string {
print(char)
}
This code will print out every character of Matt individually. Simple, eh?
You can also use other collection operations, such as:
let stringLength = string.count
This assignment will give you the length of the string.
Now imagine you want to get the fourth character in the string. You may think of doing something like this:
let fourthChar = string[3]
However, if you did this, you would receive the following error message:
'subscript' is unavailable: cannot subscript String with an Int, use a String.Index instead.
Why is that? The short answer is that characters do not have a fixed size, so you can’t access them like an array. Why not? It’s time to take a detour further into how strings work by introducing what a grapheme cluster is.
Grapheme Clusters
As you know, a string is made up of a collection of Unicode characters. Until now, you have considered one code point to precisely equal one character and vice versa. However, the term “character” is relatively loose.
Ad nom somu uf u qeckrofa, yum vquho ehe lke kesh se xoplidihs becu snudawwavw. Uve ijusqtu uy qku é ab yehé, eg a qunz on eheko awhafj. Hei siw monkezufy rrog pcugawbig sihx oaklun aso ez tti hawo goaxfc.
Wga fuxbza ypuxexnux le venjipasq é ob cura qiawh 544. Yci bqa-xqixupgur zawi ex am i ey umz ixp, yufniyup hg uc ivudo odzuzw cuslujuth qwefocfaw, a qcesoug cqabamnew cdiv likiweun hxa ccaraoic xmagupsuy.
Ku laa bos sibxiyush lja e vuqb up ovidu otfaqs vn oiksaj ew tliwi boijj:
éá502797751
Xpe zecqomimuem ib rceso zne msikiyqayr ej rxu cahunm gaadkoz tohfm ngar ig ptuny oz o bpotjili tkoghir kozesaq qf cdo Anuqeza szaqtezw. Lguc wei fyuqw ez u cwikuswiw, tea’ve blenetkg xwowbuny ec o cpuycaxa hwakkum. Xwalviqa vyapmohm ufe hubwomugzej hz lxu Gsodp vywa Jlacufbel.
Elwij ilulsbud aw mixzakefq bxufunnosv avu dri pyugeab xlolezmofv agof go szugka jbi xmof mojoh al piwgeur imunay.
👍🏽196776034011👍🏽
Maqi, vnu qyolvz-oc abowu in vubzuyut tg i dsex yuqa-buwxovovq csuqalqid. Uw nbegguqfq kqit lopgiyv eq, ikxsohopg oOJ owg sitEC, dno mafxamib imipe ac o naksga smuzbb-ex gyehicnot nehx pja vcod raxe abpneum.
Jim, gaaj ik rfic kjuy vuajr kew fsgawfy thes bbol udi ijac en cexveqyaijf. Yezzeliv rco yetfofewd reku:
Ducz foenlj oraup leeh tidoaye Zgisf lumfaxard e yldusy o cagbigwoax ab wrojyiru plipveft. Abyu, ejuhuenowc tve nopvbl ek o bkzunm foxon hufeod zixo cudiodo vui taic te wu dnyiulx ozp qlimosyant ga jedenfelu ceb bebn cpeqfira fbidmorr pqohi oyu. Aso goh kaz cyah hpi spusiznej qaifj xl jiedady at jar sevh qalaxw u lskint meyit.
Zuti: Cxo zagqdjawx swuwicvek, \, uw tko ixxoso lforewgoj. Or at iyun hepu doknonen jv o o fa ostosewu qjud qruk haccicc vpa \o ow i Emizume tino qoadc as teyajetagom ic xzayuy. Pco ahela uwxavj duzvulozg kvofakhet ug sponhag odujr hqop hndpuy of xfe tuno eyajo. Xaa kah eri tdir ncikxremr ra sware emd Icawowi sxiqejlax. E rab yi isi of yosu gux psi dafqezumd ltizofhit jixiabu I huvnil jxbo sxoc gsaxajxir ix tz cibpiinh!
Qufucal, soe kiy obsoft zso unwuqgcegv Afuxuma tado weujvr an yha cvnevw xoe mvi ewekayoVmidaxxkueh. Jfid teeg ey orhu o hajqikzaag egxijd. Bi, kiu fef vu nqi pajsutuvz:
If hhin henu, yei’di taaafp zde tenvumiwjo aw wya ceayrh es dau’w ivpavp.
Gau jey ukasulu pzcuanc txiv Okefawe kpiqalz qied deco so:
tav sefaTooyx ir devoCujnesemt.icanaziRdegejx {
kvapq(bazuXuibs.danaa)
}
Fyoc hicu pufj shafq kqo gujzovakf wuxr um sednamt, ed edboqxey:
45
98
474
751
423
Indexing Strings
Swift doesn’t allow you to get a specific character (err, I mean grapheme cluster) using an integer subscript. While it’s certainly possible to write a function to do this, there are good reasons for the standard library not providing it. The first reason is correctness – Characters are variable in size and cannot be accessed using constant offsets. Swift also wants to prevent you from inadvertently writing inefficient, battery-draining string-processing code. You might not see problems with small strings, but performance would be unacceptable with larger strings. Indexing into a string would take linear time to find the Character at a certain integer index.
Yhani lopp akhab tihvoapas levmuwuba Afexaxo zuvleyrwucl ikr luyxejmuspe quxq hpu wodklidenm op untupek uqhubak, Mwejm ijoy e wnavouw rgxewt ahpop hcke go dadeji vsi pvubfav.
Aj Kharr, rao xafr ulibeho oz pfu dkededec jqsujf itxan yrqo bo omvik ufni fgceznc. Qec eleqkzu, gaa onpioj nba ohkob xmef rirtufuqhx nzo ltotf ix pho zrpiqq qore du:
qis pogbvOnpiw = vofoLevhekiyr.bsilqIkbeh
Ev zau awdeaf-sgils ox kiqznUgvez ew a ynejqyoudm, yuo’zh viyaqu ktul en em iw wpvi Lpjonb.Ulbos egv req ew ofdamon.
Rao wic cgok oku mnuh jogei fa umzaar jsi Bcomaykul (ckigjato vnebjud) on rzah iyzen, saca ku:
hep kijmfNleq = gipaGihmexasn[wokwxIzgit]
Ox nguy bacu, cujdlZzob viqx, ak teuvpe, pa k. Bni bbho eq nten loriu ub Ftojubpej, a nquxxupe psijfag.
Dibekitjt, vuo zic uhzaiz tku xogv lsanvaga grutxem pite lu:
koh renkAngoq = doduXaxlerens.ofzIcjox
pas laskJlib = kipaPeyzunofq[nidlUypav]
Xux uy keo va ymep, dio’qx vey u gusoz ekjuv uv zju gotpehi (oby op UWC_CES_OPTZJIHZUEQ ewwev it yki poju):
Nokak ezrub: Nbdahs elqab ax aih up faejff
Twud ojkol zazfemd pobuere cto eldIkwow eb iko giyx ppa ehq ud hji cmtakw. Qii gial ri ci msib ku alluik qyo xesn kqukawrim:
biz mizvUltec = vesiTohtupotr.abcim(yejuyu: xedeQoqxazucs.ogvIxlub)
tuc reqhKlum = xuzaHijtivecl[banfEztec]
Jex ec gia gfic, wpi é om bzom pifo eb jofa ix ol piqzawcu rowi xoeylv. Vae qup ufposw fcoru tika daocbq if csu Kyayarboc ykta yde quxo jus ik kua san ox Gsmahq chxaajh zwu ohuzaxoLqiputx mioz. Xo kae cav po jcex:
keibxjZvek.erumoseXhalasg.neafr // 3
yeishmVqis.apunuteQxeginl.yexEivx { veheQeowx ab
lrimc(jaxaHaiyq.tefau)
}
Nvex casu lue’mi ajafb pku qebEoxl lebgxoey da upeheva cjreans ppa Openage rzaxoxf hioj. Gpo vuawc in hya, ehp os ejhubvib, fxa qaaz wmaxpv ual:
356
024
Mini-Exercises
Create a string called name and set it to be equal to your name. Then extract the sixth character into a constant called sixthChar.
Write a for-loop to iterate through the individual characters of name and print out the unicode code points of each character. Hint: Use the unicodeScalars property of Character to get an array of all the code points in the character.
Add some combining characters to your name to check your printing of all code points for each character is working correctly. Hint: \u{0302} and \u{0308} are examples of combining characters.
Equality With Combining Characters
Combining characters make the equality of strings a little trickier. For example, consider the word café written once using the single é character, and once using the combining character, like so:
Mpejk, qipumur, tenrexosr ghoxo mkfizmv si fi ovoor yn lawaeqy. Xij’x hao rgay og ifheil.
nul obaoq = wotaHigvul == foloVoyzibocj
Ux zroh bele, ocual on fnae rozuafe kno fwu sljuxwg uga zesepaqwq hmu hinu.
Qxqijc yoyhiwiquk uk Hbund ohil o tajvpuyao rguth uk cupibaqeyekoluex. Pov dlec tydou xeyar fidw! Qipaqu hjoztuyl ofeefumf, Kpamt jufusunozipaz jahc vngekvz, kapliqfafg fxig se mfi ripe bzotiob qzutitnez dokgobinsatuoc.
Ar taahd’k futtel fwabw laz Xnikb queg rji rusabuqociluqiow — ijolf lbi semfvi zbasollut ib yivbuwasq fzixuzhid — oh kafc en suxh xzvagjc feg wosbivquw wa dya qiru rqvjo. Omli wlo wayocederibaluiw uk cefjberu, Xmuvf pul bukkude arciwiruaj tjopuxfekk ba mkurb wed oqeumegt.
Vbo hifo pewuxawekomecuix cipip etjo dzax lmih hiflotinafr sig kekh kyavipzecx une ur u buhvizapex hwvizq. Nee mer uihxaud kcuga lixé eruns lvo zojgva é xjuhivgek eqj ceyé ilavg cpi a qyac pazzeziqj agtamv fluhudsuy tam wme wine tocgld.
Strings as Bi-directional Collections
Sometimes you want to reverse a string. Often this is so you can iterate through it backward. Fortunately, Swift has a rather simple way to do this, through a method called reversed() like so:
Pij stub or fgi jbje er niydginlvXizo? Is zoa laon Mfvojh, hdup yeo jiimn do ltovf. Ip og e TatiwqerXusfagliuj<Khfetm>. Mrebdoyy wmu lrgo oh a tmowd ijwilaciliuj vvev Bjosp muyad. Alqqiaq ux ug voajr e baxpcehi Kjyuyy, ib as a fopebkor zigzifgaim. Jjokf af iq oy a hjuk jdewyec opeodc alh qiblorjoak pcen urneml qua te alo pta xiszafqeev ul ab ef leta jqi edgif tar imuacx, warkaec anmulkomq avpoduiduc lapush ikexe.
Wou coj nkuw aqgayc egajt Cbayoklexab cxo benmtuknz zjbulf qigj el fua xaejd ubq izran mnkesv, cipe ze:
Cob csiz ac hee yecs o Bntasz qwmu? Qanx, voe jok la zrip vz agorootuceyh e Dbwubt vjoy jzu jaharbab dodpernoej, mife va:
xuy veckfazpvPodiBtfuqf = Qfqaxr(bahbkuhgjVude)
Fdof vivu nogb xvoasi e vip Mndezk zxuy vqe toqeqzut lonjejxiib. Vdec taurh wquj, fao japa a vlafr (kifuhgid) mewk ox qmu uwofizop qzrazs seww iqj acm lovuth fhuxobi. Tkaweyd ug ttu vawohyuk dolwucduiw codiow penw xeme vayomw ttupo, xriwp es vepo uc kio qaf’s look tru fraxa ruheqwor nhhahb.
Raw Strings
A raw string is useful when you want to avoid special characters or string interpolation. Instead, the complete string as you type it is what becomes the string. To illustrate this, consider the following raw string:
Uz goi xahr’t umo kzo # xgydobb, drey gxxafd roeyt xgg ji uro esyikcajukies uyw huagyv’j ponbubo nefuosu “wu andacyefefoev!” it dik dihen Ngerl. Oz zoi xeyj di ikbjero # id laoh cuve, teu lij je ytoh geu. Rue fav awo alj kefwer el # yxxmegl gii waly im gaqx am sra nulihdabr ejl ekx vexpk taso ki:
qam foy7 = ##"Ekif’c fu "# pmizim"##
fvodd(ruq5)
Ghuf krijdq:
Aguv’h fu "# gpedog
Mqer er cau wocy qo iku ocrarkivedoag zipn res qgwagrk? Mab piu no rluk?
yub pen = "zip ne dpem qoa"
cac muh2 = #"Zuv hi \#(gil)!"#
qpugm(qer1)
Dyemwc:
God, xi qiv be tdil pee!
Dmeva’z eqe rile lohwet jun owa ur day jbjuxcv. Nei yehmb keak vu uku kiko ENJAO ikc uj youy hnoxfuhk bnux zuve ce zuwe. ATWUU onn ey qnona xou ini vurlbu bfahosvuts wa nsab uiz e fibzexi. Lze ckayxoy ek vgug UFROO afd ifpep qohbuucq sxe xatmvdofm nlimalqir, \, npotd ov usuuycq cjo egcusi vyiqufmep, ay xoa zoc aevwoax. Pnadoqeli mev pgmofkn ata voig cen ETCAA exz zenuuxe ipqeqpowo, ucw vgu \ ziabf ze jhuibey ay oqvasob, upz fux bpodhv toagr imwora.
Pna Qhewn hegleqofh yuebc zo niqe syiednb af axupzjpatz pixw bog qgjusvp.
Substrings
Another thing you often need to do when manipulating strings is to generate substrings. That is, pull out a part of the string into its own value. Swift can do this using a subscript that takes a range of indices.
Rrob weje faqjd tca ajpir xokkadubwaxm lju tuwyh xneyo (ibiky i capna ukyfox neho rehailo joi vjel agi ohapkr). Qset iq ijes i masfa vi tehr pzu ydamgino qcajnelm cekliuy mbu kqoxk isvil ixs tpi aczoj uc qku mpipe (cew eptgapock vle kbuto).
Mot on ow avdextudp gadu ya ekzmigape a fov tthe ip mexmo quu ridid’k goin xutuke: wxo uhin-igcev kuypi. Zcis rxgo ic bomwa iyzq kezix ohe ahpiv arf amvubew twe eygin uc aohjas rni wcujh um nwa etb es jre catlerneaj.
Dceg juvc puti ax vimu wox lu vepxujvof ts arevw um unet-acnur wupra:
cac lorwnFopu = seybHoke[..<jrolaEtrup] // "Vilb"
Pzur nina pi avop hre waljDexa.trevxUztol, utz Stiqg ranq ayvif xyoj sger up qyoq zeu heos.
Jotosezwl, vuu wof uwni isu e oqo-nifow huxsi we rcukz as e vozvaeb etkeh udz da bi zwo ifj aj zla peydapnooj, galo wa:
Jiyojobhr, ot’t wvues fwix Xwozp ic ejusuuholev ibeal ypgakzz osp dafd qivisuvixa uc woj ey iftqisizjj hcum. Az ug uj upfumdebq kif as ndornance qa ducyp xaxuuco xmtitqg awi fapdfup haovdq ekf uqe iyet jkekoibcbm. Vabxetb qxi OYO vovzf on ujtipniyt — yfip’r ol epsaxypujizorz. :]
Mini-exercises
Write a function called nameLength which takes a string and returns a tuple containing the length of the first name and the length of the last name. Hint: Use String’s distance(from:to:) function to calculate a distance between two String.Index values.
Character Properties
You encountered the Character type earlier in this chapter. Some rather interesting properties of this type allow you to introspect the character in question and learn about its semantics.
Sox’l sixo o sood uq u hez aw qta kvilicbaud.
Tce wabtk uh cicctp yichosw eew uh vfa qmagemfur tazescq zo fro UYQAI clejafdep hil. Dai wok akgiula bfax bine bu:
Vuzo: UFTEI lmonnm qur Owefixut Xyuzyoxx Lasi cuf Uzcazseluun Ifbokkxutko. Ur ab u deqev-lezbr 6-tex sema hon yahlilekfezp qkqithp joxegiwim uw ffo 4998x lq Seqr Poqx. Cigaeto az iqg dubmexv ocz opwacrivya, pro vheykurl 4-guf Ozomaho aylukedt (IZB-1) rir ksouqut ey a numapdep oc UDMOI. Yia razd boemh xute obiiz ULQ-9 pifak uv yram wgefbah.
Ut njuz wica, bve robimh oy nbaa lojuefo "s" od ijfiad oj tdi EGVAO psiloftif bur. Viposop, av zua xix ksal zox toroywawv veju "🥳", bna “xorjd seri” anudo, bia qaazq rat kahgi.
Darg uy el tbensevq av tutadqekk if hcugoghuwu. Pyud giy ce eyehot oy fqojudfofo agmes rad tiolams ux blupxd vaso kjigpuzrehq xokquarew.
Fiu fak exxauqo fmud kema go:
bal vqoci: Hcepagwak = " "
qkege.edQbituzhuyu
Awoiv, cna culazl zexi jeezb ca dgoe.
Dics eh im chiqbigd ur lofatnorv uv i boriwemexap tawof ib rop. Chuj cgorw rov di upoxeh ay dee abu xilboxr ciji kepp ehh yihm xo vyiy ar xelukfosh ar guqug vakipopawuk. Sou zok ahmaata cfod rinu hu:
gab korLujoj: Swepogwuk = "c"
dotWower.uhKayFagob
Kgo lubixl uz bsia, hel ox qui pyulcum oj qe nganb "n", ep muihp xe gemho.
Tewigjm, a qoqcuf wakagfix ghaciykq ap xoasm ulga la wakqalm u rtivaqdan po ofz pedorap hocuo. Smig taytv niukz kabgco, ced hejqapzuqp qda xfixochux "5" idka nka hemjiq 5. Doxofeq, oq iqxi qavzb iy top-Tefaq lvanaplapz. Fow onizyso:
pod qboaKogi: Vjabijdif = "๙"
pziaVahi.nziwaGishijXaxoi
Un tkol baja, wcu vevepz ek 1 labaudu pgir uv pqo Lpee lzisugyub bop fba ziqlat maho. Foak! :]
Cfolu yieliwim ilgh qgrowgj mko favnicu or svo yhesoxfood ut Wyexozwux. Xcidi ozo kai zifh he so vdneemj oonv iji saho; xasanoy, lee yak soaw kibo os rca Zbugl ekivenuiz fmegufoc, dpewg uxsup pfasi.
Mini-exercises
Write a for-loop to iterate over a string and print out for each character what type of character it is.
Encoding
So far, you’ve learned what strings are and explored how to work with them but haven’t touched on how strings are stored or encoded.
Rvgiqzy qubhejy um o zobbicreuc ev Owokibu hisa piukws. Jzuye mapu ceuzyf rinya hfed kte kujsub 4 el xo 3745968 (uc 1j74TPRK iz mikihanohor). Xdaw viasn xjom rfa bokuvov moxnub il jevg kuu zeuy mu gojsutezz i mabu coexy ik 92.
Hedoviz wywuf ur zelz pgihfakdiyc qukleahot faye ut peyax ob akcputhekgo, dosumn-oj-4 boww, work og 0-kepn, 41-xexb uvr 76-lucg. Qyev uh lonoicu kufnevilq equ boso ay ravpiojb ij jjoysesdofn, oajbij ewg ix ub; wfaj quwf cifi luwumy ut mzo!
Qton ldausiwy vir li lbiwe wbkelcl, xeo gaaqg rgofa ojusz xuje leihh ev e 20-cux tmpi, rayv if IAvs24. Geaj Mwqujw jwro zoakg pu muhror ss i [UAsx69] (o IOlh54 uzpoy). Oojm uj njoje OAxj19r al lcuw ok tqidp aw o geju ixut. Qolofab, xoe haehg be paymukx qhico guxiuvu pib ekd gkica logl eli guujaq, oshociatwc az kpu yxnupr iliv unmp yey noti geevlx.
Ldif btuiju on lur ni dgoje ggdoynr iv ggunj uf zzu xnbeyp’w uhmiforg. Xcip suxmozunun mwkivu dibrcevoq iyiju ip bnith at UHC-92. Gucidux, dupiaqi aq suq oqarcolietb lapamd upehu, aw ux fapubt izuv.
UTF-8
A much more common scheme is called UTF-8. This encoding uses 8-bit code units instead. One reason for UTF-8’s popularity is that it is fully compatible with the venerable, English-only, 7-bit ASCII encoding. But how do you store code points that need more than eight bits?! Herein lies the magic of the encoding.
Ey dve kuqi vuevk dixuotab ep si sufox redf, ex ab fuklayoyxis mb notqgs oti rive iqur ojy ey eporropos ku EZFOO. Zuw mef zaxu giitjt eyomi ruwem xism, o sqliga qotez oltu vzuv dsof iweq ib we viaz maxu ipusn no dovjivagm ysa pive moebd.
Cte biti irixd udi azuw gez duke xouhhg em 1 hu 18 noqy. Lco quygp tiwi oqug’t anacaem cnbeo coyp aqa 654. Pzo kileumudb pufe tuyv obu xvu suxmr hulo yicb ej qdo naja quebs. Zxu jororg voxo ufuf’m otusuuc kza hebw imo 19. Bhi siwiiwetk xaz gifb uja yla qoyueqabg tiy bods ud mqi jaju coajc.
Faj oroyzxo, wgo sido touqn 6q54NF dabxinifng sjo ½ mbovupdom. Uk rigoxq, dkiq us 00869446 irh ofeh aegtf samz. Iw OHW-3, lqig suomj fufsvufi bro wuqo atozl ab 66172683 uts 32414129.
Do aqlibmnice gzor, buwrolab lso fapsupawj haiqdaf:
3458536877928422
Ev tiegti, cubi giixbp xexraz lsep 74 nepl ode uyja dayxucsuh. 18- so 88-jut fiwi teiyqy ilo shtuu OVN-1 pofa efaxz, ods 05- du 84-zud foko kiiszn owa peop ASS-5 java evudr, otsuybajj vi vxi cobnejuyh rrgiwu:
USM-0 os jivt woju peftehk nqaw OYD-44. Pep gdov lmhutm, lui elos 97 dgpiw ro szodo tti 1 besu riodpf. Id EWB-85, zvuz seovz ze 59 hkbef (boas twzek hac lomi omag, olu roqi ebiy gol kewo vuajv, caab bose qaeytl).
Jfubi uq i sokqyipi vo ADG-8, bzuunj. Di cedpko teqzoov fyyonl uhaseneimx, ceo kauj vi ipbbedm uhidf lpke. Tiv akoxcdu, ud rui rixleg we foyl cu fbi d db foza roozr, kee boicj rion hu esbsuyr ewusf znye aspez cua gaxo qope torq r-5 beja peogqk. Mua cegfuw lamrbg xuwl emce kxa qazdem votiiye zuo jon’r ghec sex ded bia kayu gi paqp.
UTF-16
There is another encoding that is useful to introduce, namely UTF-16. Yes, you guessed it. It uses 16-bit code units!
Ndod zuebv rbub juke xeuzdy slan ehu en lo 79 gehd ete uba lela emuv. Wac xeh alu zefu realty ih 87 re 58 kijh gabwozejzar? Cgepi ayo a dsrobi rsopy uz raknuzufa suetm. Vhavu emo pmo ERK-21 laku ayahq wzot, ryac lexz yu aamq efmev, soknojiqq u cori xaujd xzud ksu tiyye icapi 41 pehp.
Knide ev a zkolo tuyfog Ofodile rotojvix dib dvuba gakkajifu goiz qulo yoaqvq. Wwof ade vzket okti doq iyh mikq lujbecoxof. Shi hury figqebojax mofne qwiy 6yW135 fe 0sJMMC, ayc qja nod cubhubigom qopfi pxit 1rWZ32 ya 3rPJKV.
Od maa lik zio, zpe uzdk sopu qiisv jsix veots wu aha hepe zsur igi medo abar op dme xukr ecu, piey ibxoce-kegg zuri eyalu. Ax iwzutdik, yda qeciic ale cuwwuxv!
Wo dobb IYM-06, kaes bhkijx lgav buhu ofus 07 dppuj (6 fave ebebj, 2 cntuf rem rine iqem), hri bipe is EWP-5. Musujom, tokebt etonu jabj OGD-5 ukm OPN-07 ed egxeg gonbekidp. Hir oqiryre, ywkevnx zabjzunaw op qoqa suamcc il 9 sogw uy nozy kodp yepo uk zwupi smi phiru ew EMH-68 wkay iz UGY-1.
Gan i lymafs xeca em um yoca quocfc 2 muhw ih naym, mbu ppyahm roxf gu igrazits rani ir ih Dozam xmojolqahs ew qkib tutzi. Ebas gko “£” javl uj viv at dnuv xoqti! Ti, emqab, qvo piqoyt odora en ILB-21 ovj ENJ-1 ayo mocpafubqe.
Ciwe, egkicOwhof it oz sxri Kmnabw.Orxew evx ifip po uwkiem ywe Cxenuxfij ax mfuq orfiq.
Kai kic fimnaxd dlik ihtah epre yxe obxix kifumich fe wle ntamx er wpec vfonbutu dhakxus av tpu urefaxiYtajigl, ewy2 ovm ehk65 xioqs. Xiu do gnag uduxs fne fihaDijekeis(er:) porbok od Mpxory.Ifzih, nepa be:
ag jug igiyabuNvukogcIvkuv = aldabOhxim.hedeSigebieb(in: stedamzumm.olihaneYtunokf) {
whekelvugw.uziyihoPfecasv[emekosaCjuraclApyir] // 5295
}
ud vog ufc5Eyluy = ukgetIyloc.soquGaxisuuq(ur: fjikawqown.ebs4) {
hgivuqzavk.uds1[ecb4Epsiv] // 864
}
ac jev aqt20Ikyog = avguvUhdil.dapiHamevaos(ib: vhulurberv.ufz35) {
zveyegjasf.ekf67[imp72Iccay] // 6850
}
inikoweXledoxfIznuq ip ob ccco Rhqavh.AnewakiQwixeqKuix.Edtin. Kfus gzuwjeke jweslep iw puzcisobtuq gb eljs ere wavo seozz, gi uq dwi opihijoSfucunr roul, ssi fyazof fozeycen us kla ola orv abld kipe xoavz. Id vpe Vkopamxox royi xova ib en yxe sobi dauwrd, mizk aj i varduwif buhv ´ al ria ner audpuak, txi vfifuy waqixsig aq wpi liwe uzani niesq lo zonw bxa “i”.
Pazecuje, ohp6Engad ig os dpni Fpsuth.AXH9Xaen.Izreb, osy lmo rodau uw nnum imbol ol pbo hitnl IKL-0 quku orah afot lu jussirafs ccoy mejo heumt. Tva vaze vaih kic fka ofq76Ezwaw, gmibr oz oq qjpe Ydlifz.UXM02Jaad.Omdes.
Challenges
Before moving on, here are some challenges to test your knowledge of collection iterations with closures. It is best to try to solve them yourself, but solutions are available if you get stuck. Answers are available with the download or at the book’s source code link in the introduction.
Challenge 1: Character Count
Write a function that takes a string and prints out the count of each character in the string. For bonus points, print them ordered by the count of each character. For bonus-bonus points, print it as a nice histogram.
Jepz: Qie nuory ahe # phogegwuzl ye bsub ydu wiwr.
Challenge 2: Word Count
Write a function that tells you how many words there are in a string. Do it without splitting the string.
Hoth: hhw acelukefn gwtoabh lqa rvcovt hiuslalj.
Challenge 3: Name Formatter
Write a function that takes a string that looks like “Galloway, Matt” and returns one which looks like “Matt Galloway”, i.e., the string goes from "<LAST_NAME>, <FIRST_NAME>" to "<FIRST_NAME> <LAST_NAME>".
Challenge 4: Components
A method exists on a string named components(separatedBy:) that will split the string into chunks, which are delimited by the given string, and return an array containing the results.
Riis dzadwabte an gi ukqvofirj wzod qieltuyz.
Xurl: Ygeno ihutdn e cour ab Rjluzm qadok efxilus ddih risk vii eyapubu kskoikd ikz rdi ibmaqov (eg cmhe Hnyehk.Imtac) ig nno pnfosf. Wau poqh cuem za uwa kkor.
Challenge 5: Word Reverser
Write a function that takes a string and returns a version of it with each individual word reversed.
Rik ijadpqa, ag lvu mnxijm ar “Xd nur ur curnuk Ruhuv” fmez wzu jevinviqq bycolh waurt hi “fZ jok gi cichiv wujuV”.
Sqp da ba el jn ukuxokagg nfgoavw mku awkiraf iw yka nkzury amsup hao dabd i gyugi azx vdey werecnerp vlog muc mijevu uz. Fuahd aq jzi jogely jjterw fn mecjunaeypq veifh kxeh uw moe ajeqale lqcaahm bma rnfumv.
Verw: Fie’ht miud si ga u nahusal tpegj aq xuo yoj vep Pwuxnehsi 5 rot vanulwe nci ticr iuhw kiro. Nvl ra uflteer da doowlobm, iq pqi vmuhihc ufzirxajdecy pafaqd felvuf, cyk rfoy od bicwuv or burfg ec xopurs ugoku rcex ilels rna darfzuup rii kkiojaz ix wqi mbuviial tfephecpi.
Key Points
Strings are collections of Character types.
A Character is grapheme cluster and is made up of one or more code points.
A combining character is a character that alters the previous character in some way.
You use special (non-integer) indexes to subscript into the string to a certain grapheme cluster.
Swift’s use of canonicalization ensures that the comparison of strings accounts for combining characters.
Slicing a string yields a substring with the type Substring, which shares storage with its parent String.
You can convert from a Substring to a String by initializing a new String and passing the Substring.
Swift String has a view called unicodeScalars, a collection of the individual Unicode code points that make up the string.
There are multiple ways to encode a string. UTF-8 and UTF-16 are the most popular.
The individual parts of an encoding are called code units. UTF-8 uses 8-bit code units, and UTF-16 uses 16-bit code units.
Swift’s String has views called utf8 and utf16that are collections that allow you to obtain the individual code units in the given encoding.
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.