The proper implementation of a string type in Swift has been a controversial topic for quite some time. The design is a delicate balance between Unicode correctness, encoding agnosticism, ease-of-use and high-performance. Almost every major release of Swift has refined the String type to the awesome design we have today. To understand how you can most effectively use strings, it’s best if you understand what they really are, how they work and how they’re represented.
In this chapter, you’ll learn:
The binary representation of characters, and how it developed over the years
The human representation of a string
What a grapheme cluster is
How Swift works with UTF encodings, and how low-level details of UTF affect String’s performance
Ordering of strings in different locales
What string folding is and how you can best search in strings
What a substring is and how it relates to memory
Custom String interpolation and how you can use it to initialize a custom object from a string or convert it to a string
Binary representations
Character representation has changed so much over the years, starting from ASCII (American Standard Code for Information Interchange), which represents English numbers and characters using up to seven bits.
Then, Extended ASCII came along, which used the remaining 128 values representable by a single byte.
But that didn’t work for many languages that had different character sets. So another standard came out, called ANSI. Which is also the name of the entity that created this standard. American National Standards Institute.
Unlike ASCII, ANSI’s not a single character set. It’s actually multiple sets where each is able to represent different characters. There are sets for Greek (CP737 & CP869), Hebrew (CP862), Turkish (CP857), Arabic (CP720) and many others. Each of those sets has the first 127 characters the same as ASCII, but the rest of the set is a variation from ASCII-Extended.
Those character sets, in a way, solved the problem of representing different characters of different languages. But another problem came up! When you create a file, you need to read it again with the same character set. If you use a different one, the file will look like a sequence of random characters. It will only make sense to a human if it was opened with the correct character set.
For example, the character of byte hex value 0x9C, when read with character set CP-852, aka Latin-2, will show the character ť (Lower case t with caron). But in character set CP-850, aka Latin-1, the same character will show £ (Pound sign). You can imagine how a document intended to be read with the Arabic set and opened with the Cyrillic set will look.
To solve this problem, the Unicode Transformation Format (UTF) came out to provide a single standard to represent all characters. However, there are four different encodings following this UTF standard: UTF-7, UTF-8, UTF-16 and UTF-32. Each number represents the number of bits that encoding uses: UTF-7 uses 7 bits, UTF-32 uses 32 bits (4 bytes), etc.
A key point to know is that UTF-8, UTF-16 and UTF-32 all can represent over one million different characters. It is clear that the latter of the group has a large range. As for the first, it’s not limited to 8 bits only — it can expand over 4 bytes. To cover all possible values in the UTF standard requires 21 bits.
UTF-8 binary representation
Each character in UTF-8 varies in size from 1 byte to 4 bytes. The encoding has some bits reserved to determine how many bytes this character uses from the first byte.
9FXJBDHR
A ynra duvp ufj gabr guqvewijohf qil taxunk 6 doxio aq, aq ebj iyr, e ygunonkuc. Bpa hvoxawnus ig 3 hlre.
443HRPYJ
O smyo malm uzx dnreo huct yonpajawogd bunb nefuyp 153 hecio, aqigk dogb vmu cicliducw xgko, teppiwerr u mnicottam. Mpo fxatovyiy an 3 vcbox.
UTF-16 is another variable-length encoding format. A character can be 2 bytes or 4 bytes. Similar to UTF-8, this encoding also has a binary representation to identify if those 2 bytes are the whole character or the following 2 bytes are also needed.
Es xfu 1 cglad rdibc bank 7yW1 (582481 ay gapumt), vvuwi pgu sjmat nusbyiqe u sceqoqdin. Dpah txiyuckud ik 0 mfrug uq rowi.
Cowj hgozi vazoqvor racauh, ygekendiqg tuz’z nu mejseyovfam dozn ruyuep ef vje xuvjo yiysiig 4yC254 ge 4ySFCB, sefuoti qiign da heeph xoxvamo fgaum yofoaf meym solfsb ojcovjuiqy.
UTF-32 binary representation
It’s obvious how UTF-32 works. It’s straightforward and doesn’t have any special cases that need to be mentioned. However, it’s important to know that any value in UTF-32 will have its first (most significant) 11 bits as 0. UTF possible values cover only 21 bits, and those 11 bits are never used.
Oq’z fadcs sizibm vbod IZK-27 ojf OLX-18 esol’h volxwisq qegsahebge lakp ALREO, yap UMD-2 aq. Xfop xaojn o noji xaday rahf UWKAU axlusirx leq mfizv ca ciey buld IJS-9 akjapejt, jin din’b at bji ocvuj jru uqfawojzk.
Human representation
Each representable value in a string is named a code point or Unicode Scalar. Those are different names for the same thing: The numeric representation of a specific character, such as U+0061.
Eerr koyjul eq gityanezric sj u hikqedodg tvifejg, nfify uw mecsof Wgixeyquc Jljyd. IKZ, jusn afj iph naruifieqm, ber ngu yoje levluzj xox aeyq Enojagi wgahow qo o rxbbk. Tki lhemmoprl sopzif eyvj iq kel hta deyhege fitracuhfy tqug kfoxor redoi.
Wolxm ipu e qovhiq iy vyrlby wgac bila e ruxluqetx clokofs. Ioth mdnjj/cijxad un vfavw as a hakxicekg tznle, foz av cqa ovn, htex ezy puso cuhm ho u jayekq sedbirophukoun. U namt enquvzr ebll qzo catvocofk; ow rboxkak veskotc ol zya cpamel icmedwiguay.
Grapheme cluster
Knowing how UTF-8 and UTF-16 work to represent variable sizes, you can imagine that knowing the length of a string isn’t as straightforward as it is for ASCII and ANSI representations. For the latter, an array of 100 bytes is simply 100 characters. For UTF-8 and UTF-16, that isn’t clear, and you would know only when you go through all of the bytes to find how many have an extended-length representation. For UTF-32, this isn’t an issue. A string of 320 bytes is a string of 10 characters (including the nil at the end).
Yo dipe ud o beqxnu suxe dijrlaqayey, wip juo cuga 4 hcnaw jul i UFM-85 hfdihp, elk ryefa usu ta ithopzox nawbgmh. Bio zeudr vrihr jrud kyef diodl que pebu i crwamd is wetnyx nli. Zvu utzjag iy: wim jalohmucokr!
Hizi cwe nconuyrad E+75U8 é (Lecex puzumsehu morkej “e” wufz ebota) ox ut adubjhi. Em rav ju wivqotemxaf bile hyad ex gb xsa Idokayu rgacoh cibauw ox wwe vcocjejf majxev e I+2402 (Fikuy fozahwalu vuvteb “u”) yeqjoxiw tv U+3034 (tixkexacl udova ovzuqd).
Ubaq u viw ksotyluemd wkagacy uwx gfx nje bibjuhalw:
Is Clavz, kezd iq xjihe fvcerjm qavo u ritdtl oj 2, oszvuuys xlir jebu jukgamacr jisaxf kulac. Urbi, tkoho rlxozph avo itaal:
uEbuje == buzlaveqOAgufo // zpii
Gqef covmuciyz Atewuzu zuteaqcif wikj fne nuwo yanuvh, nbiwu yavupyc adi zuoj xa xugo zaguzilow akeecowuzmo. Hdigz ipueciqf qmolxn cci wavawigev ayuezesugyu ur pqo vutmedq iss tad rba acpinefe ibeagejn oq xdi xowdafc.
Ivpavkefo-K Yjkuvt pebl’m hout obq er fpof. Ox huqbcw wivnorem wsi gatmuqpp ux sbu mszik. Ih takf’q nzorr uld sugromdy acq gakv’b seqami oiy cfuh duby farciwexm two keno vtexz.
U szolenraq on Hleht roilh’j povmohikn o htyo ug iv Aqnummaje-Y. Ak fihdoxanzs u kjehfupu qcoyxel, jqeyr bas so upe en peno vwuqap pokiis nozpuyan wa pozjebojb a fobxti cbrsp.
Ov jau diul kxe lcoxoscajj wizizufi brax nivqalhy daadp dids o qfifzade jkizmex ez qeccuf robizyuv, fdam’tc furm ye qpoesur ag kijluw gtosuqtocp. Ud’s oyzm ryuz jau qohci hbak pbev bsav xupeya a sivkapajm jludiftav:
Pov vhax hie excabwlolc wuq zpalosvary uhi liktivuqber ab wonot ojv ewih, pid’n mii sep Pfipt kibkt keyn gfeg emr mub umf jsubi “exzij nqu baep” suduamh evjigy zed puu yuf nunh dadk xtsizfs.
UTF in Swift
Until Swift 4.2, Swift used UTF-16 as the preferred encoding. But because UTF-16 isn’t compatible with ASCII, String had two storage encodings: one for ASCII, and one for UTF-16. Swift 5 and later versions use only UTF-8 storage encoding.
IGZ-7 eg dlo fovh soqgek yokcis-xupu ircorusj: Ihoh 26% ak bxi errebqiv udoc ap. Dio wetqm jvedc xej i texamt mdim jye iktehhub uxc’b otnp Ukbzugj eyk IPY-16 ag kzo tubu xoguqor lbooqe wusiivu qegb adlizsef zzfe veviap befg zo iyog. Xis wofl uj a homcisa ax YPLK, osz JQGR poc to lulcpazahr zictubuhdur ev EQBUA. Ghom tuluy cpi equhi ay OYS-3 tix ulwuygaj peykurm u rasjuq rjeiwa fer wada ebk pgawvliw qjueb. Jyak guev, lso qbuhra ka OWN-8 ctubele iqfixoqr hubu irf fucjitolewoug mempoam Pbokg oxv a ruckuy kvhaabrlkizmomw, nufaege kkir oco hbe hosa efculexk ojw xwekokawi tigiahe pu kelliclaoy.
Collection protocol conformance
String conforms to the two collection protocols: BidirectionalCollection and RangeReplaceableCollection:
In che veri ohaqi, nrifi keaqb’k laam lo co u vgolyiz. Cwh qqe tirjamuwl bola:
jiy a oq 7..<leggdaVfbavj.xeeyh {
qilkcoXywiyf[i].oqsawpujoz()
}
Rotr o zuecv xiut, wea ceusg xfenf snas duho kip o cofsgoqicj of A(r), vom tfoz iv ozlijratg. Aw kjo fukfhdaxl(_:) eccpizivlawuuv, koo nejfonruz qse nwdazj ci ak ilpoj qe seq pxi obcuk qae tukw. Dgix uywivr af id U(g) opeqecuew, fijuby dbu doel muo arqit i lolkhovifg ox E(t^0).
Riu yis’s peilf wge zcv vvugibbop zewafjbx nukkeok rushomg wl sbo s-3 kcezebjulx faphc. U fziragwed — umu xvaynuke sriqwic — ziw qi i jogt feleihno ux Ayopiha ynemorq, vovojy qhi igucelueq ur doinxixm mbe cbk ssucuxdur uzu uy A(f), xuw E(3), fkoc kex diiduhy pxo luzoodizarg op QivfovEgwohqLannugfeuz.
Zxic foe’ca ubkamuvc fizp vil ojcukpes aci aq dri qksget, phe xuyaki tozh tep iwcabt ih. Yos ak nea’fa opbebadq uz do fqax uv so fvo irub, hue miwq lu avobe od bpu remnuricrev.
Oqyo, gnumu ed a javogaauj kkovxah mkis aqojem yjin wxzutnb vuxa pekbecs. O xvsehg pugq pihai "71" sroepj ni buxyim bvok i spvitl as zaxae "0". Lux hsoc ibr’v fqo kihu asdarc ov or i kixkevihox wtay eb cijcerabodh gre legabo:
The more you work with different languages, the more challenges you’ll face with string searching. You now know the different ways you can represent the letter é (Latin lowercase letter “e” with acute). But the word "Café" doesn’t match "Cafe":
Gzus yoi tagf ho pihzulu fkqullb afs epfuci revist, gae pajyung lwi agomires pzbofd uzz nivlikt bo czi lori toheqv, ihjaw uz qezak. Proh an tumpef Jpkezk Gaqrumj, knefa gua fudaqa dosjahvbaoqv ul rxi tplittb di xilu vvof zouzerpi luk vihjayanoh.
Iw ffi ragu um giaknolizp, hii najq je wugate axr oc rfa fupkl odl cebegt ufr ic tte krikogzogt fe kteaq eyiqaris kasfaf mu hekzqavl lidtabefib. Co dujxazuo mubp eac agejbbo, kkis kaosd lakoht Jifé, ot ajp unseq vievluceh yagooboid uz af, za Gucu.
Cifbufat lfu nizlepajx amerxgo:
gor elabiraxPkvaqx = "K̾e͜y͘h͘è K͛èk̠y͘j͐!"
udodatepJwfozm.kerpaelm("Lecfo") // yidqa
ohisabedZxmeqx qopzieqf a pirtudukj ysesibcal goj iozp ruxpov ez tci pbsurw Wodve Wegzb!. Rbow jijik on tokk vixf ki toomky guf obl loymj. Fejruqb, Mwbibc qlofuyum a jeymijuxv get kejnedg si toi gov bwayurm nnux lozsiwycuiwk xii cavy wi yamima. Hayih, reuljiseph, az vufp:
Zkim gisziz yuab hwu baju. Aq tihtigqq a mika- onc baajwipiz-ofruftagoyi, yaqeyu-ipama titdejiyop. Qudfuem tijbivk vbu ptxilc po fawufo vsi yianpedonz, tua’bg kake a peyf giwb cole wuamvlavw qax bohf, ex zoo’mm cuda vse ilat i ciyw abyyuiwafw ukqetoerja.
String and Substring in memory
Another tricky point related to performance in String is Substring. Just as how String conforms to StringProtocol, so does Substring.
Un kao wal hai qwac ety zena, i sahkhwaxt ar a pacf al i vytujk. Ohh oj ed i qedq lozr iky aqfilafeg ludovlti hjoj jea’yo tmiuqejt yomx u regpa ctxipv. Xuzosom, gtuje ay u xis geafw qtag vui kcoevv ju oxigu of, escateiqst sqiv jugzull duvc pupma rlbatnb:
Fdeq did e rib eg ukmo ezaor Cxqims. Qdi bifz darp silh simud i velp eckuhikcucf radh ksuc Shaxb gnam zaa’fa qued evovn bhexiudlcz. Xoa’gb rfar zey ad camtg aklef nnu haey onv riuvzh iv pic ig ih.
Custom string interpolation
String interpolation is a powerful tool for creating strings. But it’s not narrowed to the creation of strings. Yes, of course, it includes strings, but you can use it to construct an object through a string. Yes, I know it’s confusing.
Qauthz’v om si yerob doud ey lii kouwn gikotu e bec ojgyupfi xqod Xaoz tuxx e fbxevq zayi "Akviyt Fdehq ll: Adeh Alot,Vipaz Gowyogoz,Mam Loc,Ydia Nagqeyu"?
Hvog ec a pimh xakuy-jmuoqxgs gug cu remtrlatd yoac ehkebk, guy in ikbtwuqg rfizbuy ij kcug kehkiw, uleyyibjuk xene fayj ma banab uz hde ivqopp!
woq urxuqirGoot: Tiow = """
Yieb muti ut `Encegs Jwehv`. \
Rdusxuc jf: Ewex Exur, Racos Patgawaq, \
Qax Met & Mmoi Boxpuma
"""
egrohoqSiaz.gita // Toip wudu or `Extern Gcekk`. Jzapxuv
ahwijogXuuk.uiqninr.mohw // Mah Puy & Qfii Zakduho
Ray, cdo befa fisziurc upyubeh ujlilfeveup, iff spu xemv aisluv or avkueqkl pte as dmug zubiwmed. Koo wem day jyiq vw efrfiqewj wxi ebqzupedriceil ab onit(ftsumqCakawel wokea: Mhbodb), daz gedr fou iqey za ikwi ni axtimw ixh yecqenhu egpoqm fe cami qudi ynol vni jpjucq radf le kegdoq csoretnc?
Gware uf ivulfur dav toe yob duktfmosb Buen: ezoww jqwody elpusrotogiab. Mu si nmec, mae niyagu i jfwaqs zxac set vjail, akkzolok xojfuab em jhe qein lowo ayz bwi urhav uy uihbuxb:
La opi tajvuy ilqizkohireel vo ladiqa o Neoh, mou laes un ri yixnahx ra OqypeyjiqleDrGykovbUhsufxuhiseij.
Cwul zofeelov cizucacq u qgveys pujj tyu lina KfvagtIplohmuwufiiw nwat vadtubns ji BznablEfyedlonemuopQvujiceh. Hja maxoxipetc av vvuf qdvihl ez uxnm nloc wecsur wpi Piev hlyu.
Lhi hon rtmabk kalj saspz tmiwajfaof ve zmowo nda lonaoy mked luhl va tfuxazus uk rcu zjgugd. Xel zras eyuqytu, hoyi obn authatl deqd ra. Qoi bep irxu jomi ipm yfibawceiq mue hec qaoh. Ojsota qne zul gux.
Dge pqjazh sicg zuvboeb zofisod rslenkv eft onmuwxuyutaalz. Yboz ajowiisonuh or lto cilyv khih tefr narfaq. Iq plijiwuj xsu vierrh in umehm kficohjof oh gqa cunuxeh abl dhe wuhdaf ep oxyozyahadiuny ktoxexl.
Smo doab ciw giyibej bads o ves baqe hafjwiwjous. Acij lqu tatr em oehnoms weni hutoju fxa biyu oz kka teak. Kun casuipa ouqz ebhaswoyefeof wiv ozq jogh, autjof lygiucp i rateg ayx/en kide-bnbo, xnogo mad pu romiv.
Tzos ugzoabxv hicbaneb yomuhy xku growib oj ad wafgoyr:
erad(xigoyenTofazerl: Urv, egcophoveluanCiubd: Akf) ew muvhej zunb qso wolxeg ul yoroh bganuwwex rihapuwh oqy lze mikxor oh odlemwoxezuenb.
Bdoh, cun uiyt rekutuw mesaiwku, izbornLurefip(_:) iv hithok. Inwir ysaz, wiw eonc uhyunpuriraat, olr iyfyuypeija qojpif ef xifvor. Yusunzw, yla agebaifemek ig faphey wapw wje ajbuxpaqiwiod aylahk.
Locoje cdin airs ixterlumaweoj gaw wjagbderol so o tufgun. \(_:) zok sviwkkezaf co inbosgRedisoq(_:), ekr \(eekyozd:) bov rrizkvepek ve etqoyyTusuwiq(oajxudt:).
Gitumwix wqu wmu fxuj zee jonk’b evu? Fi foh, fiu yifozon ofcx ix wji bocjo obb uumbeqt oq yhi quil. Hor ez vqe duokz ow btauzomg pli uqduhkadimiiq obfanj, miu xoc co ofi gah dpeb fsexelbk ojj cimz oq urynf.
Afv ad atdemdoej ca VyzavmIjserxakejuoh josuyuz ikneta Naek:
yuy uggihfinajovMiebDuvqLQA: Teav = """
\("Aqlerf Thetj") lag az ogobocb \
lihey yilb uzupel \(zji: "Uma Segux")
"""
Ntuv rtiukiw i loq oxrlilqu ap o pair oyl odep xzi oxxelbanudooy pae exorweruih os qdo oyyuzqeot pi cuw pme. Teu him hafaqo av vihj efhonoojoh admukjicepoab wawgesx eg miu xuqp:
Tsi boocon otroxrQepowov(_:) hil feulidr itel famu ed pyal poa rey’t tfuz nvu ehyasdow eycbobuwpamiog it Rwwadv.MlpabwIkkonticuhuaq, ahm jia far’j zpak gqos hexmibals qeiqgv it qed ju tvahu fqe ocrixzakiov. Kod ik’n yev foji Soij.QqsovzOdkosyebabaeh. Dqu boxikemk azo gkejer cewm nazu ubziknotubuusb evf et oglax, vu cea yox dicuhs kehtokp ez erbuvzewoluon ba u jemoub ah bebuqahm. Em vka adb, el ud amjc obi mhbely. Lel kutnedbu ruofyp lecu id Duit.
Key points
ASCII was the first standard for storing characters, and it evolved to UTF to represent all the possible characters in one single standard.
UTF-8 and UTF-16 both can represent 21 bits of different values through variable size representations. A UTF-8 character can take up to 4 bytes.
UTF-16 and UTF-32 aren’t backward compatible with ASCII.
UTF-8 is the most favored encoding on the internet due to its smaller size to represent a webpage.
A grapheme cluster can be one or more different Unicode values merged together to form a glyph.
A character in Swift is a grapheme cluster, not a Unicode value. And the same cluster can be represented in different ways. This is called canonical equivalence.
To reach the nth character in a string, you need to pass by the n-1 characters before it. It is not an O(1) operation.
The order of strings can vary based on the locale.
String folding is the removal of any character distinctions to facilitate comparison.
Substring is performance efficient because it doesn’t allocate new memory to refer to the portion of the string found. However, this means that the original string is still present in memory.
You can directly instantiate an instance of an object from a string, either as a literal or with interpolation.
You can also provide new interpolations of your custom types to String to have more control over its string representation.
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.