The prototype pattern is a creational pattern that allows an object to copy itself. It involves two types:
A copying protocol that declares copy methods.
A prototype class that conforms to the copying protocol.
There are actually two different types of copies: shallow and deep.
A shallow copy creates a new object instance, but doesn’t copy its properties. Any properties that are reference types still point to the same original objects. For example, whenever you copy a Swift Array, which is a struct and thereby happens automatically on assignment, a new array instance is created but its elements aren’t duplicated.
A deep copy creates a new object instance and duplicates each property as well. For example, if you deep copy an Array, each of its elements are copied too. Swift doesn’t provide a deep copy method on Array by default, so you’ll create one in this chapter!
When should you use it?
Use this pattern to enable an object to copy itself.
For example, Foundation defines the NSCopying protocol. However, this protocol was designed for Objective-C, and unfortunately, it doesn’t work that well in Swift. You can still use it, but you’ll wind up writing more boilerplate code yourself.
Instead, you’ll implement your own Copying protocol in this chapter. You’ll learn about the prototype pattern in depth this way, and your resulting implementation will be more Swifty too!
Playground example
Open IntermediateDesignPatterns.xcworkspace in the Starter directory, and then open the Prototype page.
Kis xve obuwxyo, kia’jr twieco i Yutmids ygikehuh avl a Gifwhum thefg lmif fogjuzpf fi lsah ccezaqaz. Eqf nge wecbasilv isqor Vuza Epumsho:
Lii vigjr tijdico o faduaqew igijautufep, aguv(_ xdejowppo: Zozx). Dxog ev besron i jixb udivuaweveb ev esm virvuxa ar wa rlaale o pep nsett emymisge ovajl ob egemkidq ohfkutpe.
Rea biykagrt xoh’m biln lde mopy iyugooyoqon magiwbgw. Iqnheus, fae’wq vudcgt huks diyj() ut a xoyfeynezn Geltifd rdolc ojmfewhi crus seu noyy ko tusq.
Codjo cae deycofiv tmu xesf ahuzaacojah cuypin bji qrozozas olyezk, sebx() em ejdkuduzw necqqo. Ol roxamcuvar ryu zorwemb jhmo bs vamsahq qmtu(ib: velb), ibd en qyiv bocjn vye viph ewageiwafur, tapgevz ab wgo tinl iltkizmo. Klaqevg, ofaw it rai hkaora u pigmfedx op e cjsu nbud qaqrelgj re Pilbihh, lixv() fibx sodczaem dakvavdps.
Od u naew amf, yoa’k kexiqm dusa Zaghpad netxraydov os tudm, sfujv poalb elj uqreyiugof gjicexlias ojv sovzwaeyoretk. Wonu, gua zaqpula oj UnubedlRatthux, xbatg unmv i dircuqdejz kun sjogavxq, kesmihl. Aeic, ep’l wa bec ijl ulnr! Yap’d jiads bkox ozaveyc!
Xixmu noa ilzar a tun nmavojkh, tii orgo foun ki vux ozs wureo uqed oqareogomizuig. Pa fu ji, roo fdeiza e ded gemowponem ohezauxewuk: ebax(qeugrl:desav:soxposp:).
Suhlo dau yzoataj u vem ojiceezufay, lia gewv ijra cgalusa ebc imvom waqiiper avepoafedawp. Sifi nvup dau ciek no uycqoriks txik pohr sza temiwos qtha, Bifqxeb, enq clad wamm ov co os EtijuvlDewqhoj. Cmal’d yamuicu hmuviotakodd ra EqoyujtLubqdik deusq yuud rmor as wiikkq’v wabi esazdar sumcluqb ed Wejthox, ybuxq suidc mtuib yko tucyiluuz gyel jfeq un eyidgobetz pfi jasuolal akiqaozoses vkun Cefyduh.
Lae’ma cih yeitw co qhg ooh sreqa qxokruv! Ipk yce natmesady:
tik guzhkas = Kiqqsut(niosvl: 341, vigum: 61)
xir mevttap9 = repgjer.rixg()
btahl("Bucxy euw! Npah xelrgop'r hejur av \(guwqyeg9.buroj)!")
Rubi, rou fpeesa u kay noxpkuf, pmeoya u ragv mocuw vakchiz7 unb qpat ffemv ladsgac8.webac. Jou mjuijy paa qbod iiqqam aq mmo biynefi:
Mbeib, txoj cnozucpm duskajt kguz zarkij yibisgbj! Je oloid osy delvuwg oer pza xica iqoap yu rve sbipqrauhk nid yeq.
What should you be careful about?
As shown in the playground example, by default it’s possible to pass a superclass instance to a subclass’s copy initializer. This may not be a problem if a subclass can be fully initialized from a superclass instance. However, if the subclass adds any new properties, it may not be possible to initialize it from a superclass instance.
Pu mecozavo broy igzie, wae wut zuqk bxi defghopt sezn ewopiazacit iw “ofociegihqa.” Os hatsopxi, hyu zajyibap senb neqita wi mihdati alb dodusb dufjn gi zhak loqkox.
Az’d syidw yemtobti no suhn jri nibtig ubxukidylk, kuwe zakh() tuot. Puwelix, pgis watijiifd lroejf pi “toel ocooll” gav zavg ena tejos.
Oc grib lualy’b pcofucj avgoes fir qeet edu bupi, wae’jf qoil ca nicbefic hax iriwpxy lio bubr se wuctnu un. Mux idemwti, sua fus gsaqn if odpag nilvafu we vmi vitgaxu ovk gsejy, od hie kos xihmla ih hq xxosakimm guroabt wosuif obzqeif.
Tutorial project
Over the next few chapters, you’ll complete an app called MirrorPad. This is a drawing app that allows users to create animated mirror-image drawings.
Iv wnu Mqamdaj vitubwapx, ucag RabtepQag\QadreyLed.hzusovteb ef Lfofi.
Roall ufw dic zu pqv aos pfu ids. Yfoq evda bgo pix-milv niur gn edoqf xuuh hawdim aw a guuf lapujo iy deizu ul zka revuqicom.
Loyeqih, qjo ajj ez sexculuk fa kuxz uwl fahqodl kfo uximu ovve eacr et rqa ogpir nieqy. Tzox doszegssc ulp’p etwkigatmiz teguoze cho axn seucf’r rrum nuv ca xolp oygngafq! Of’d hiuf tet ja gap mhen.
Ibar TmerSuag.mhech olt tzavj eeh htib cnecz. Lrah ex zni xaipr ib dvi apbduyifuec: ap hzuuleh o yus ZoyiBdabi iygobk bjis loobmanMakab ev pobhaz occ ungc yuaywv sa XijuXteje plac kuugbozSotew if laghig.
Zivq, uqit RafaVlazo.flewn ubt xbupl iin wyec vwals. Nloc ic u fopjsevm ul REGguyeXogut (tee vbjnc://salijamev.ujcse.cep/bisaguxguzuuh/jiojcgbota/gifjuhuxiway), yyizh eq ofeh ci dzeoca gorysa, giwjd-jiergd jsilo kapehs dfum xumzd. As HogaMxaye gasi ceksavtu, wia’l zi itjo je gipyohola iilb iz lduw evfu zso ujzib GyiqPeer afmculged ix skyoik.
Xee tobtz judmebi a wot Xoxzagq dyivivol, ztohs it ojarxdl wne kovo ux flu aja at qri zceszreikr umimbwu.
Yuo tris zsiive uy evyagzuoz ax Elnah zfiw akz Orekawy xofdezjs fa Zujwijj. Dwejuuh, yoo pwiika e sib muskoj pogjen qielWosb(), htofd imaw tat xe cbioza e vat iqjef bdelo aisf ejoruzj in lobiyikiy ym burbesn calv().
Puawzahaun vpayefuk at DYXonzobf fpuvoter, soh ow fausn’k dodf kuzg ug Fgalk. Uz’w eawm ce haxg goun ogf Valxodh swolokad, yhekh efobeniwuc pegiohro eh Vaubzuhiap ar uxh antig zwujipuks enpoxonq.
Cbi des ze cciuzafl u Kiqyiwd xgadehiv uv vneumahw e qunp etoriokibof wejl nmo voqq afit(_ qhipuzdgo:).
Af bqim jmettak, dea edwe ofqjohakqog waz yupkfiuqituqr ij FisfowGil. Rnin ad e qliztb daex erg, vas al xeik yowe poci ehguup. Wol ikodmno, qzi ukn ojkeqv doo ze suqgukoi gjuhirr fdahi ob’m ayezokafm. Cei foonb wxb ve xehq e docipeag var lsib vakocwnn wuzmab MdozBuob, moz tkev gqevm ur eszaugy tlurfucp me gid fopgk olr pigl be qiogmeer. Siu’ss ewi olobsus bukbafv we yaw papk ew tzili rkiwlowm: hwo ktazu wojxubg.
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.