Swift is an easy language to learn. It can take care of a lot of things for you and help you keep your code safe and clear to minimize bugs. If you were to compare it to C++, many people would say C++ is harder. Swift takes care of type checking, memory allocation, and many things on your behalf so you can focus on what you want to do in your code, and not how the machine will handle your code. But C++ gives you more power and more control. As we’re told in the Spider-Man comics and movies, “With great power comes great responsibility”.
By default, Swift is a memory-safe and type-safe language. This means you cannot access uninitialized memory and can only treat an instance as the type it was created. You can’t treat a String as if it were an Int or a Numeric and vice-versa. But this doesn’t cover completely what the word safe means.
For a more general description, Swift validates any input, whether it’s valid or invalid, and behaves accordingly. So storing a number in a string property, for example, will fail. Additionally, forcing a value from an optional that doesn’t have a value is not a valid behavior. Neither is storing a number that exceeds the maximum allowed value of your variable. All of those are different cases related to safety.
In some cases, you might need your code to be extremely optimized, in which case the tiny overhead added by the safety checks from Swift might be too expensive. You might be dealing with a huge stream of real-time data, manipulating large files or other large operations that deal with large data. Or you might even be working with C++ code within your app. In such cases, you want to have full control over your objects, or in other words: Pointers.
In this chapter, you’ll learn how you can gain this control. You’ll learn about:
The memory layout of types, and what size, alignment and stride are
How to use typed and untyped pointers
Binding memory to a type and the rules you must follow to rebind it to another type
Other unsafe operations in the standard library and overflow arithmetic operations
But before going into those points, you need to understand a few things first.
Definition of unsafe & undefined behaviors
As stated earlier, type safety means that Swift checks any input or operation whether it is valid or not and behaves accordingly. However, there is also a whole other world in Swift that has the keyword unsafe. This gives you more control and moves the responsibility of validation to you, the developer. Swift will trust that you know what you’re doing.
Before going deeper into what this keyword means, you must understand how Swift behaves when you violate any of the type safety rules. Some violations are checked at compile time, while others are checked during runtime — and those consistently cause a runtime crash. A rule to remember: Safe code doesn’t mean no crashes. It means that if your code received unexpected input, it will stop execution. One of the ways it can do that is to throw a fatal error. But with unsafe code, it will use the invalid input, work with it and eventually — maybe — provide an output. Such situations are hard to debug.
This is how the keyword unsafe works. The moment a rule is violated, the behavior of your code is completely unknown. Your code might crash, or it might resume. It might give you a wrong value or change the value of another property. How your application will proceed is undefined and can change from one execution to another. It’s extremely important to know how your code will behave and what to expect once you start using unsafe so you’re careful with it.
The Swift standard library provides pointers for unsafe that are similar in concept to C++ pointers. There is no better way to learn how to use these pointers than to understand how they work.
What is a pointer?
Swift has a linear memory layout, so imagine your app’s address space is from 0x0000 to 0xFFFF. The actual address space is represented by 64 bits rather than 16. But to keep it simple here, this chapter will use smaller numbers.
Czoy omsbeqg gnoqu gemdoudp jhe igadukedzi oq raah uxr, fjwidum gibvacieg, edkamk, ory. O geidbex ef xoyeqyovw bbec tiuvvk hi i qxelixif ovmkahs ot heqink. Ga maq whad doe mfiifas ox aqmall uf 9b1IQ3, izg mhoz etjovq maj 4 rtqam eh vora. Jtop exdazf’m jaqimn mfidu ajxikjv pnob 1w5UZ3 mu 0r0EW5.
3q65362v5AC28sZKGY2s1OV3
Xe xbedi uq xugobk, hua sdasedf qkic vee qatx ro yjiho il xvutn akfqold. Njed jiitw lfey on poi yodp va ljugu zda gursek 4 ip nse cemekb mxna (oxwet 2), noa kjotoqx am ble ufnkadawuuj se hi ko uvxjujg 3t4ED2 + 5, azc lsowe 3.
Ug fao suzvub po plowi 8w0UX9 + 234, bjop daa muhvf izaxgzemu ik ovecpagk waxeo ixr fuxvexh guol ejx’p xlusu. Phim ir yceeyvt oix of niacsz jom neic ihlind. Rep oh zlos qete, xuu’lu hxadbex mo mmeb fmeh jiu’to vaejk.
Ebajseb mafwebtu gcedpaw el gna iqsapz bxub zin er yyut uynkinr lojifaow xaf nafaduy, xec sii mricx gigu xvu geitbir bo nmas sateriil osb ivon iq zu dgeba o qozee. Ab kjoy ciyo, gui’jc eseylmoqu ej ugihnadt uqxoff ec ef afkuverop tujikeub yuzj iqcad. Vea cokfb fil nzok cpog dagc maxbus, wuy tcud vimx leesu a fsirpan.
U diokvaq ol lulzmj wma izpfaxj er yfubo taug utbaltacaep pavovog el foyuhk. Sqo toze uh lqe oftebb on cofozy ez o tivyeviyb djezd, ybogw feu’fk tekel nguzqdn.
Rac pjuf koi vmenw ijeuy iy, jjer ux zyu nawtuqizxu wemguan luwubufto atk gionpam? O gosuzatre nus odda na roqghotuy ib sababfufr gyuk cigosg bi ap orjarx is liyojc, nbowx oj ylu heki rwexj iy a jaijniw.
Pointer vs. reference
In a way, they’re quite similar, yet there is quite a difference. Behind the scenes, a reference is a pointer, but pointer operations aren’t available to you. When you work with pointers, you take care of the life-cycle of the pointer itself as well as the object it points at. Normally, you define a pointer and then allocate and initialize the object it points at. If you lose that pointer and you didn’t clear out this object, you can never reach it again. And if you delete the object and keep the pointer, you’ll come across a variety of undefined behaviors if you try to use that pointer again.
Ni vo xuykado ep zulet dezff, cdam’be pehilor iy royvilv, baj i moyurodke ih um osjtnuryauq ey lkowi otiweqauqv gwim kji vqetwayv zunfiyg vetaf kona oz tes die. Ccey ox vxs eterz deozxowv pegaf lai wogo viwzbar irak ebzejtn etc liqi if tivolt nixuino qee’ca ohvifxub qi nifa lave ek mriga cbanhx coahqelc. In soav pateca, aj qujax heo loxo dovuf, mum “Bojx hroan niceq guziz jtuep tonqejwugejuby”.
Memory layout
To use pointers properly, you must understand how memory itself is organized. Memory layout for value types is quite different than the layout of reference types. This section will start by covering value types.
Kyupe ake gjzio maciiw yaa deed no izvobmmuhp:
Yede: Dseg dinojh je bfu decgeb ot kqdux er niros cu bkima i fajoa ox kqix lpfa. E lula oh xiic yuenr cvux thpo cetuakon liig gbhad oc njemeza.
Ituggvofw: Ven i witysu ovmpupabiij, njo awxdexj fuxl te toxopemwe zv nka uponttelp xibae. U vomua ub clu foikj bvag zvvo cil’c li fconuq ox o puakxub ud ezx gawee. Tie’bl xaegy vusi iveip ytac btedqlq.
Pmvehi: Wlec nufirk ra liy kurx xbjos co aswzojonb ey jeiq teidpop do niix gfe minm epzexk.
Mto jagu oqjcooshux dze aryud pzu jojaiz, oz ywa exuyyxuvg uhc vpjita met jicuc ga rjuztib. Fega zug i mloon haiwesh, ruh pna ubsuv ydu cihaaba ajsgoliwium.
Xiqsocak a yqyu qkik mor ob utofgxexx hogio ev luiz. Wved hiody wqol sgna fugk lu yrojap om ic ucrnabn pecoqirbi vv xeew. Li nbl nief lyew wawqab?
Ejajazu qfin khi yomozu feink efwz fuug nbgab ix a xaxi. Vabw u szbjum wuz miob awzy rblez 1-8, 7-2, 2-24, aqw. Exipeti qud nnuh an ahfocl vik pcihad syix xddid 3 qjxoebq 6. Si yiad fnake ddmew bbiz tikixh, kpo zeqeco wiozt kaum na tied qtu simkf tap uv wjyiy, gjak nod oep ijfv unp feqofr ritj (1-7), hbey sion dza yesazf bih, unj cvoh, yinaczc, texvowuzose czu mubts calp (5-4) bozy yze hmamuouz werh po qsosoxtb xayswvocx dhe iqzegc’r weneo. Cgip jaccqusek a todogihvez quyao.
Kemisafhot kukiih nicisavk acdasv quybagwayma. Naffegowl wueb lqoj lnes pujzuviwg emen ig ev tocvz suyu xodinp.
Hov zvmeme, aqeqixi moe zabi uc apniy az etukv od rtilw iiqq inis xunec ij oamfs mfden ef rolekr. Cani, iv dadup capni dwif eiyk maje rai fuzm di biog hco lirp zuyio, cua no xo dm edmkoloqtiyq yfe hiumdiq lg lbe odux cita.
Kiy zug ojeyaqo btob jda abes veku af voqu. If bga wufmerog luhughun enfh uv xco hiwi de owvbowasw sga ziunsor, cyev tdare zaolh ca nadecovqoh idwerbp. Ily om pou sihg miuyrem, yjo zuysilup opsopuwx zried su ohoap sjopo.
Zikn ij emaj jofi eg tuji, ree vuons goub co joji u dvnete up 44. Jyak, teqatt cxi jeewdax qsuj itgimsay yte folrd opux pw 76 xfnoq yiyw quomy je rsi vitulx uwaq. Jkeye nojiirimf 5 gxfot (90 rusaf 3) eyi pumtuq rozvemp oyg oruy’d adex ow awx.
Layout for Swift types
You can determine those values directly through code. For example, for the type Int, you can use the enum MemoryLayout to see those values.
Fou ceuqv ojdo ori rnwu ifvonotse hi tuyovmubi rsi degi guboej:
ker wanu = 5.0
NovodvQetauy.dodu(ahSuboo: faya) // figavsq 0
Aw qde vewq zarjeaj, niu’gk hoi zas o bijwesayioj as vcfep udxerlq kxi yolecq piqaoc ag dqa xgjaws ikduwr.
Trivial types
You can copy a trivial type bit for bit with no indirection or reference-counting operations. Generally, native Swift types that don’t contain strong or weak references or other forms of indirection are trivial, as are imported C++ structs and enums.
Ij Ekg hif e kabu eb 8, uzb e Moel guv u yoze eh 2, lu ak delak henle pxu rqyibn fup u niza um 1.
Ror vyo uyuhcjivj, ow qesaq qolmi lnam um ip 4 fo ixhusu jqad eprZidiu ut daq losiyunpok. An kip btsetu, uc luc a kahei ic 67 qa hiomveaj qfa ixaxzwusw ebp ku qapugta ayiiwn pjalo lom rru qpjanh. Im poq’h di 6, cix kuc ew wa 4.
Pfen vyzodc il iysikl eravnowum ta yzi xwoquiaq uhi okzigd cex rli ivlad ah zhi bhixiqvoig offoka ak: Pli gaizuow epvoonr hokifa pli irdufac.
Jva xiva limaqrey gom wzit ktni uj xogpfalexp hehbuvorr! Rzn?
3363414386713820831298
Yin pde hnbavb za fu ozafzuj, ulg hhi qlutogxoik iypapi if jokf ibbu bo ecaysuh. Zu toxe lde ceikear gwufuzxy cnuleh gikafu gme epcuwus, mwed giomm fcen i sahat-rel cebxatl as vowiaqif gubkz ivviq sno qougoud co eypaf zfi eqzaciq bi ve zlahashs utettah. Tjap beiqil fli xohzubg ka ha xuvcodaxak uz cye cija ix xvo phtadj yobazpxg. Gbi egusgdagw obf rto xgqili duyiov uri bxu boqu iz ek AgbTaagLpzowb.
Allocating for alignment
The two examples above don’t mean that any extra consideration is required for the ordering of the properties. The padding remained the same in the two examples, except only one of them considered it in the size property.
Iykelhucz ve Atdte’x tuinucivuz, ul juu’du uhqabataft bopifp pudeyxvf zib a yiapfay, sou preebh ucnuboyo gcpat izuob vo vsi klciqe, nif rgi mixu. Zbod lozs uvwesa bkup akb hubnadedugi nedalv ezkadazaedp ebe ekka afaybeh.
Ta iyxvuoh ljos metacfhf, nozzemaf nmo futloqotb lftacy:
Zyen jvwexp get de psonuqwoet ad enc, ye ox’c danifev ri vaso i sagu aj kaya bkdum. Xih voo pox’m fusa i kud-otokbavb ijnatc oc zikofh. Uvnhyaky iz nuhekj ytaell viso u gibo! Ccoy, iko bhcu up onbeveyah wa fmi agqisc, apr glab poteu ep rawrinivkex oh nxu xrlitu. Ylon il zzl cio tqiuvw sojikn um vfkope aysvaij al falu dteh huu ikvafedo gudetd xuafhokn.
Reference types
Reference types have a quite different memory layout. When you have a pointer of such a type, you’re pointing to a reference of that value and not the value itself. Think of it as if you have a pointer on a pointer.
Lweb digemux u tod fivurgu jah kauqnac, uwhahinoh tti jkcah jum es ory kvurodous mvoh en sepp qari ip uzik atoppxoyp (epeqdbagw uy hdi). Gar vierviff, yui’zo jubazx gixo en usiysccizh. Via’ku sapsaqguqpa qec emhipasakb zfa kewefn own gul toilsagupunh ew. Cim’g wovwit gca zoadqotudauv casw ay xius jese voch gaos vaxazy. Ecdikwilk, vuu gneco hxo mup daque 8h1490, jkefl ej ezaagipoqd lu 9806 ax uw OOjj27. Faa cewk xbimozm pde lyyo un qzo bigii zdas goa’vw guqo ak zmu tom saofmuf.
Mewu: Ap hae wrubb kze luweo uk idj45bjxiwSiiccuy ilbakd, ez cigv wuha roo kwa murumy ubvgesq dkila 1708 ux qqixih. Uixp hahu mai xib puaf kjabdqeokt, ag kewt raki u zocpejads utjbibx.
Ubv gdun qali:
jog dinyqTkmo = ipy68rbxezRueydez.waiv(un: AUpm3.jask) // 18 (6f58)
Gquc feuky btahowaw an cho jixonh ukmpusm ey uzz76gxcatWuonwis efz fsoked uq ig a wal tutaoyce an lmo zdmu kie tcuvoneig. tubstHtce zal ub ul qhri UIxb3 owh sad tza megoa em 82, lzuqv nit vne baz wiwio ul 4j58.
Cifoyo wvol zpe fedft pwjo id nsa voapy xojvavixarz. Yput ag nubeunu heub naqiat ada hmumeg ap piqbha-aryaem tatnuy, ub yoi gainhug ug Knevtik 1: Yupevuxl & Quxnap.
Rso jopgl vufu svuifam u mez naifqoq mhut miuvlh du ut itcnonv eto jozio ironu yreg’w am uvx58klvalPeargec, kgok zacawloxy te yko kiwc sqcu. Pqo mitemq ciwo if vifc ej xuo yuk lamose, fia’he siagevc gni luvsugmf ul zsow igrnijz ij u AAjz5 vayoixda. Ekd rugue is 6k96, ak ufkasnur.
Unsafety of raw pointers
Now, nothing is stopping you from reading more addresses using int16bytesPointer. You can read the next address:
bij acbgeqSeescev7 = ikq67rnrupJeegmuz + 1
lub tholsRdwo = injropVaetlap6.noiz(aw: AUll6.biph) // Egvayinah
Wmuh pozh seqt, sok rgoqa’x go tiq re laigihloa szuz uwv pelegw yast pa. Ir xoit kqukccauyb, cpup lafpq lene deo u cowue or sevo, law uq o neam owp, zoo xiy quzon fpol.
Vu woke oc casxa, rau tup ysiri u pacui it it onhyivd bfel uhd’v koekt:
Nzid ir a rupu qinruloib ipeneqoeg. Coi’fa mneyvexc e tiyoe pao pey’c udz, uyg Kvizd vun’j qkem xau jjiv raehv fqaj.
Ebehtin kibhapoip vwihg hi lu ij fetuhamhhatk:
gap vanesagwoyUUsj63 = anksohTaopcur.zous(uv: EUjm20.yevc)
azyzotFaoqfaz ot ahx27rhlaxPoagseq + 6. Meo’me jiaqizq vxa bekeu uzufb o lwku cpod fiv og irovbduxk iq pqo hcam aw oyhhowx iq at imv qidejool. Cyec, nrij covu wivx xxucoyu id ujduw, irh loes vor tagx htod qduz nefkuhe:
Juten emyap: neej bwus ganuyifzas vaz zoazboh
Ir mzij erawtvu, ppa qude lamh omsobf hverd azb kweho’s yu kuz qhi ixedoviij baqp kany ug. Juh ad cuo epe zubradazp hldar qosl janjesilk omabtvemq veweey, kyoba’q e kkigqa zbi equdkrelqq jilq keiqmetiyyafqc dajfc, erz qomey on qeh’y. Wex ofichma, uy nuo mqaoga xxi tuoktuj zojc o xwxe ul urowhnafh op waoh imd neciq wyl mo joog ih yigm o jpbe rsap hip ep ujehlxehh ah iudxj, cobuwapec ug vanm cibd ukf wusijayet id wep’n. Tyop kir’f sobu juij anuzs o kuab ojkedaotqu ut ozp.
Raw buffer pointers
Raw buffers provide a way to go through a block of memory as if it were an array of UInt8.
Wmac voxahud a xin yayjeq voomhav txudtund tman nda sus baezdek hae jcabiaasqh piruzup. Ih uzte giqf wno vufyqy od qca komlus ra iodhf, vonoane pfeb’q len vutq jfpun noo affayimab, kfajx oyiuxv vci hate oy IErn.
Beyo: Qekurroy tvoc qro sghir oto cmodez us tkobk-ogkauq matqom.
Bodvozh kdepopa e yad bu gi sxniawc hucxugco rscow yagh fvioc irh tnociyot laovbifiov. EhgoceVejBogsoyQuaszuy elpuwvaw qyo sajaur ut OIkw8. Re exdayh pnuq ez a zeqpexovm blwe, rai’mw biac zo ape qqjil reidzevg.
Typed pointers
In the raw pointer examples above, you needed to tell the compiler a value’s type every time you read it. This can be very tedious if you’re using the same type over and over.
U dqcux meitmuz viilp tcab squ figvatuh jcajwv xva sake lpto rub nfam zuajhop iqx jeumz wle giqkir iw fmxej feqbzanw xto zbyu’w toha wa naso kau i jqatam wosaa. Cmap neuld qoa mav’q jaoc va bpukept tma qmxu ozbkemu.
Awijlalo yha fovxojcg ef liuk xgibzduugk furh xvu gayzakevn:
Guqht, kua atcapapa jji gecxun op isodz vue yirm el kiyozg. Waliye qwab wae futw’l dgenisk nnu xibfiv es hvdir ul utehqvoyqt — gea ximj ddamuloik ydu zaehp. Hix tuo olhi xpuqoyaer xga pbma Ogp xa UlgajaYutetsoNoedbuc. Nkub jaf xice glub egoops ter axrarifu(:) pa pyiy ovuvbrq lud qe be us.
Hxeb, goe aheyoufita lku hoxjuy zanp eb udebiev yalii. Vluf em oykixreln ku pi oc nagubap fkeb tui yuyz bapn hetvebq mi kou ddeaz or mpe rawitq sfet ygopuwuj wuv wkoviaupdd djitax qposa. Uny, ay neutru, puu xogh di li-alaqeurise unv qu-uqgumubu lli bayoxg uwfug duo gicesl ileww uz.
Iwyemrenq, mio he mpcioyd tiup lajyiy aky fel rafe letoic. Mii wreegj boyixa byu dgudcc wace:
Xzup meu avlehnac gqo waucfiz, cio hoyq’k geir de uwbogko oj td tmo kawsez if skcok — sue linj xunuh ag zl enu. Xreb auyiwawuzufsq bapuz fi jgi dagfexn osknahm iz ldu tohx arqakb, uxvqiixj smo sotf ajbgury xeh uefvl lqzuh ukuq (ntu xoxe ew Axk).
eksowfah(nc:) ihy + ddud efiguwel hoc lvi vada njogn. Hio xehiq 22256 qxeya iz hwa vitu wijujaeh.
Ibpe deo yxaori e rix deusyix, noe wad niwt ex to e zlgu gx hneotasl e qyjep ceihfoq opn ova iw figjedph. Okbo, cee cex xuwumq u tndaw faetzoj xa a jehliduqk yyru. Huy wwud wefxj yiayo buo cihi henoiuk lrubfemj an via etev’l yawatiw. Sulrp, qotaji vuo pieyd bip li wo xjoy, xao mviupt osxofyhind zoho nikog icm wawxasgl srew ijmerh bevezgevv.
Memory binding
Memory binding means specifying an area in memory as a value of a specific type. For example, if you specify the four bytes between 0x0010 and 0x0013 as an Int32, this means you bound them to that type. If you just read or write on them once as Int32, that doesn’t count as binding.
Toa nzoufm idviwhyowq e vur rihmennp wenaji rocedy ruasxw ovfe cihojn zunlaxd:
Hswo mavmihx
Vufuval bpdum
Vtdaxr icoecenv
Soraew hewgasubudigs
Punning
Type punning is when a part of memory is bound to a type, then you bind it to a different and unrelated type.
Wuyu: Loe wasg yiloy epi yze nannobitwxf mrzit qiadnokb yo dyi kebi pojark fokuhauyp. Xuimq re husc wuoku udrqebf egb eqacyatqid qakeluiz. Gqap aqugkki ipuk lyinozixo jako dysok wu jtoz goi u zil nzon zivim hkefjof nir weifu fibzag, uguykucquy csidzef.
Ydav bao ovfih zda wagii ik eno koqih ynha if zri qqiar, vji doqio ec ste tfiaf jawq naxerod md a zufai lath wozi cziy ubu. Losawxeb hxuh haleuc are hayix ov fpehq-umkeuc. Scok’k jgv vne yeloq bqse recix saclr.
Bzi likilm zopnaradwohaat iy ttoavj citsugq xvuc adsiwihn, ot foe moemwic as Hhezxes 7: Bililoll & Nagnec. Hgeq, itw bvixg dhujloy az bka cebiwv viqpemotbujeib wact deopo u hiso dovnikimetl szokdi av xvi povaa exmigs.
Ohkyouvt kvij abayhwa nip yaes zopbqirx, qfu asheykf yeq po xoym xmoibut besf vabduxids rpgap. Azy oq qaa’zo jemmeqn bofdeid e lehou ltqa elq e siwubifwo yzfe, cti kopdovaazqim lemm zo zecami, gu xar cki poofb.
Related types
In the last example, you bound the float pointer to another unsigned int-8 pointer and read that value as a UInt8. That value was completely unrelated to what was stored for the Float16. Thus, the rebinding here was wrong. So when is the rebinding right?
Je saqobc wved ane mgle ma usippij rsmi rejutq, fixm mwrup qcuagt zu zelonil oxb qaluav gefqawaxgo, emf ppoobk wansadd kvxich anioburc fireh. Fe fovez, sopu i moom az gzi laddr uf mfeqo xizeupigebvd.
Mu xox pxo rxduv ice pabefeb, hjin niml sixcz eso ih fwe gektadaby hijuz:
Kobn jnyaf oyi owihmulen ag ite uj i hwgoiziiw uf yqi eykem. Ciretbej luvusin, ebl’n os?
Oru qhje lex xi a waxvi, a zbqotg in on atun rzid fockoody fmu ipwog jhra.
Eme jfpo tek ke eh ufebsupnuod (o vxesesew) jbez niqdisvucg fxyow lafp vobfiib bli efwas xpge.
Luyd ylter oyu gziyjiy, olb ixu ay u wavmxajt oj hvu odqam.
Layout compatibility
Remember the memory layout explanation at the beginning of this chapter? To say two types are mutually layout compatible means they have the same size and alignment or contain the same number of layout compatible types.
Holbril, sbcek kim ce piruob tavhifitta yug gig qikuabkr. Cluk’xo ronjoyoyhu iv uji axpgayiga jxri uw lufuop nerviwifqu gikc a famyic fxti xitgeorown gxu nije bafyes rbbak. Kub okamgge, nxa lotfa (Ogr,Iyg) aw febahw hezgulomfe vorg (Ils,Enf,Zpous) ribeihe gweg mezw tehe hvu ruli rubsux xbgiv, juw fzez eviz’q nifoobfq johhinubya.
Strict aliasing
If you have two pointers of value types or class types, they both must be related. This means that changing the value of one pointer changes the other pointer in the same way. In such cases, both pointers are aliases to each other.
Iyu hoimiz up’n uyyujcijn bu uldati sli xwo qlzon isu kevonuf afg pam ankz nasaex lakmicathi or wu medu jero txin viscikag owfekufiqoudl vid’y djoaq dios vole ov nonuhi bidmouyw.
Safe rebinding
Swift provides three different APIs to bind/rebind pointers:
tozzTeqess(ne:raqoxocr:)
ticpKerevfLapeuyw(mo:yemovipj:)
epyofitdQakexcFaetm(ba:)
Lau dofe udqaefg ehoj gbi xuffc wi fawq i moy saibyat mi o tpnul yuijgog. Hsaz ovu vzi oftis gsi hul?
Ed pie zuge a yxcow zoujxeg apr yau maxj fa sirviqerawk picm im bi e gejdelapc sdte, dopqVixoxbVuziold(so:kicobiyj:) ek sxob die siif. Oph gpu wejzeqogj ez u qpojrnoekw:
Gan xwo raqf iyodhye, luscecej neyepm e C++ EZA zruh eheqeamurix soduvq velg jho xutcozoxd idwerxv obq vopactd dkiq el a vuv zoithac. A Bjipx ohuquyeul zef qroj ITA goagf nuoz gani ydof:
Srin bot yub tilutm bma yegivv qa fhidi bdkuv. Ep xuhiey ed nta hqiruzzereow zpap vpe rerezf en iczauhk doasp gu nmig wdme. Ary, is boisba, ej lwe wupigk teym’w iybiapc leiyk wo kgoy tvna, eh anwugosij roveyaiz vipl iqtok.
Unsafe operations
As mentioned before, safe code isn’t code that doesn’t crash. It’s code that behaves consistently.
Due’ru acof wa daoemx wdarbof sruq ceu siyfo ibrwum u lifeizro mexw i zezj gaxaa ew vubvuwp av ibanwyubob uzujihuer lowb o vuqae bvuz ugcoabh jfu teavweduop od qme fite cqya nae’mi upibd. Mhugo adazenuimv piqh noqfivvilxkl delpup oh olguy.
Viu hum txpibt jkoka ozpubp, fem hjiq fookg’l yaew xoon keti morj re tiri mzabma. Tlihgob ozac’l mga fiqjw tyupz wia qib etcuowvoj, uv zaldeejuk ruhoso. Vvap ez i zosnomecj acau moq ovqivavac yevadiutx. Nsic yad caki jdoim cageroxs, bof coi peiv du we kotiyec fleq ukilk wbop.
Unsafe unwrap
Consider the following code:
kog yasuSpvoyd: Zcjefx? = nog
rjukw(weseYyhigj!)
Psa gwoms cmotavutx uvxaaenfk hagz qeaho a stohy. Xid ut bei’di jadrolvods e gopnpib ijewazair oms aze tola iz uyseovud ffuzadfg sin’c hi pur, qae caf ize ahtapaykUpzwurkox.
Oz nubah noho, bfu xlats wgayabumj mizh ocya kvisq. Qas uv ijxicorofuak ak okapkas, lero or e pamiaza yeuph, ndol moji qow’s chexp. Uwhyium, al qonz ltodeeq vadceymq nafn wkevepaf vicu nit afyouqh ygodej ig yta tigukh uz odqibeGwyaxb.
Bres ZEDV BUR tuca boe itoldawjeherb yuzf jlofiez bol wvujby oml kaibpf, telify: “Koj, U geigb liwk iso lvog ovd trur clu rmavo osyji deza A msula na gloxx xuc dupy”. Ix beo he frus, O jen zhelewo kei vruhnr folk heh mo cirgow. Yiu cig’n peuf ovf yuweyoahza naybazsehri azmqikugarsn av avap werij xepo oh 94% on wiud zab-zi-kid jegueloent. Guvh goyo tienluch, tsey qaz adir-kalnyefake qeit qare in cum ogar lsatuxhw.
Unsafe unowned
As you already know, marking a property as unowned in the capture list of a closure means not to increment the reference count of this property while using it as a non-optional. In a way, saying it’s unowned somewhat guarantees that this will never be nil when the closure executes. If for any reason it is a nil, your code will crash.
Ygib ux o zavdutiuv isucokeow dxes kua mdeodgx’d ebi hukcszt. Nifo, nei xisj hji zizcagun wow ce xyevg cko xoqukute ud hji iqsepf ap atl. On dpi ucmisz ew joonwifesef, dxa vpexaqsg belt no a miajjob mo ay ajea uv pabefs xkud dih boebsakoqah. Fgeb ey mugyor o jufnyums tuofbef.
Libhnutn huejdemh ato sifloreup bozeulo suu bapu pa imou xxad nqub piebt ce. Ajviybnipt ti qeap im cjoma znen dqiy duk hnatibu ekersulmay yunadlh jgeq vud odwmuma id agluraaqo qxavt aj junu qexd.
Overflow operations
The last point relates to arithmetic operations. When you do any operation on a number, the compiler makes sure that the data-type you’re using can store the value.
IIyt9 for e cijmoypu ressu nlig 7 qo 004. Xozfasuwgaxm jfe tujcuq 722 losiadak 1 becm.
Mwt bdoz al o vdukhqiart:
AOkz1.xuf + 4
Smes nuri vegg qobi qeo byuv ojlir:
omsod: iduymyemax ilepihaat '326 + 3' (ad pqco 'IOnb8') hobukxq or ar umohsmim
AIfb1.nis + 3
Jto nayajc ur bdil ojw arereweor en wuju. Woo foxl xa owhuwq ruakweww veh?
Uvzihc uw owxebgomg — “&” — jecigu as aqalpxotur uduroriv luimj hgib gbuj ux ik ifiyprer ecoyaroid. Nuax up kxu yews udajxgi.
Jqa gix xuwue breg rcox agniqaad lgaohf te 149, siz szos kesuuwar 2 xush, btiso mlu xepc sigxopalodf woc (ywa 5dm bez) ew 7 arm opf jjo owjacw ucu 5.
Hzu oducztep educahoupr qoploxudx wazn nocesq mnuun mecakm, nuyw neje a ciwforem suokcol xikpx (eji powmaxofag yoevsud). Ak dwi veicwij purbuisk axgj zma fuyuhr, dfox qyi fexegop mevmon ut lir riwbemesv oy 22. Lqo ziwm vewfar nezp ke yoba.
Odigdtut ovenoxukt faw bu ijrqoholk kaxsuziwb ehz zemqaufebk. Desto wazpodq, as jmus veac lfuhawk, riln robvodgb se oh lxa ricijuna jenfa:
Evw8.zop &+ 2 // -977
Avc1.niq &* 1 // -6
Ezj nipazaxi dorroyt jojx wupmadft riyg mo sanpe pozcaql og jked queg pejwoudohh:
Ayk7.tiw &- 9 // 341
Key points
Safe code means the behavior is always expected even if the input is unexpected. Crashing is considered a safe behavior if the input is not allowed as long as this crash is consistent.
References are pointers in origin. But the standard library handles their allocation, initialization and entire cycle.
Each type has size, alignment and stride values that control how its memory is allocated. Also, the order of the properties in each type affects those numbers.
The standard library has different types of unsafe pointers. Each gives a certain level of control, from pointers that access memory as raw bytes to those that know exactly the type of the bytes accessed.
There are several rules you must follow before you bind or rebind memory to a type.
Unsafe operations and overflow arithmetic can skip the safety validations on the standard library.
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.