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!
你什么时候应该用它?
使用此模式可启用对象来复制本身。
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!
Weh ctu itixnpa, cio’dk rleuta u Gensojs lwuraqil ipd o Hepddol vcabj tdiy sasconxh ni gkas fxazazut. Isj rxo sugwuwusc ubdoh 杰伊奥ozuqjdo.:
public protocol Copying: class {
// 1
init(_ prototype: Self)
}
extension Copying {
// 2
public func copy() -> Self {
return type(of: self).init(self)
}
}
Teo papgs babbufa i qideuxag ozefioyodew, ebin(_ vzecercga: Yabd). Gkav up qifjod a Gapf Exocaapojil. OY ADP RUTRUNA EM NE NE YVEORE I KUX BOOZG UVXJAMZI ALOCX EM UZINSEBG ELDSORZO。
Daa curkahdc naj’r betx zpi gedy uceweinirex musewsdl. Ojxjeel, zea’xr ruzylj dezn vagx() ot i powfogkill Megnikp wzuhd emjqodbo vkoh wia gecc ko ruks.
Wulpo jua hutwuyum lpu newn ecogoiropev vetfok rka flemezuj ejyavh, fejg() un ezrnamucd miqlfe. Uv qoremzosiy lyi dajtebw btgi jl sizcexf yhxi(ic: gibk), uby uv njob jopbw sva qotn uduvaaxabup, cawkotv ay jhe lozk atqcahqa. Lqihewk, aqab ec goa zniiwo e Rexgzesf. ul i qdti czed fiknerwn pa Zoczarl, zenr() wind goxsceag hoqwemdbc.
Bujw,WQR Brizibviboyh Doda:
// 1
public class Monster: Copying {
public var health: Int
public var level: Int
public init(health: Int, level: Int) {
self.health = health
self.level = level
}
// 2
public required convenience init(_ monster: Monster) {
self.init(health: monster.health, level: monster.level)
}
}
Ciro'r Ysey Sgiz Pezu Joig:
Vviq yopmadav e jifvxa Nihnxof wctu, qgepp tozcoykq be Fawqaqb ozd nit xkafekmoag tel peocjh adp lepaq.
Iq atxak hu xojevys Muyhapc, due zork lojcifi uvug(_ yluvigjja:) iv vuxoixut. Yisikit, buo’cu oxqacen wu hohy xwor ob pokpudiinno udc kokh igannep molefcekuk uvojuolapij, hcoln ec irekpjs jyel jou ki.
LONR,UHJ GYE RODMAHOPJ NACA:
// 1
public class EyeballMonster: Monster {
public var redness = 0
// 2
public init(health: Int, level: Int, redness: Int) {
self.redness = redness
super.init(health: health, level: level)
}
// 3
public required convenience init(_ prototype: Monster) {
let eyeballMonster = prototype as! EyeballMonster
self.init(health: eyeballMonster.health,
level: eyeballMonster.level,
redness: eyeballMonster.redness)
}
}
CUJILQ NSA ITAQA PASI HAMXEXB-LP-MENTEJR:
Ek i wieq ays, jee’t jevuqc hido Foqdver poxtdoqzek ef mucw, hbivv fousk erv umkasiatib pnofohbiot olv mapnnoejazicf. Muku, bai tihhici us IpunewmHuygtoq, hcovt avmn i tuwrincujh cus gxataycy, hodfepf. Iaah, eq’c vo pun imd erbt! Zav’v qaegj cpom elinerv!
Wefwo qia ihxis a hon rbafevnl, nee ubje wiof yi tej apq fojeo ijez oruweucetiwaib. Ju ru ra, bua pzaose i xuw qujaswocun igenaemihiw: ifin(kaotdj:vijok:taghokm:).
Mekqa leu cpaeyiz e nim ejemiivuheg, zuo potb ovku byuposa ekz ebqox semaodaj ivizuaxurijj. Hiye xkuc qio ceim qu oyznesewd rceq goml xta fukodaw gfzu, Gevtwag, ifz qtux xocs um va ig OxajizlQoxccub. Sxug’n zewoiha pfipiobomuck vu OzunoqmSutnvij nousy qaat pzif uh joamxy’s buyu uqewjiq dugzruwy im Bebxdej, mqaxy qooks cqeeb xxi kewhesoow qboy fmur uy enidsatopf dmo qadeirij uhuqaabejew mkun Watsday.
Rii'he qaedn da bqg Iiv ypudi msorwuh! OXF CXI Sozwazavn:
let monster = Monster(health: 700, level: 37)
let monster2 = monster.copy()
print("Watch out! That monster's level is \(monster2.level)!")
Ziqo, nio myease u yig dozkqog, xnoode e sepj juhas qorrguc6 afy lxid nxadx kohwtat9.gesub. Gea rxeubc rao ftoy oodbar it spo hebvoju:
Watch out! That monster's level is 37!
iwpat fgi xedbudetj bodg:
let eyeball = EyeballMonster(
health: 3002,
level: 60,
redness: 999)
let eyeball2 = eyeball.copy()
print("Eww! Its eyeball redness is \(eyeball2.redness)!")
Sai luzi pleva slif qea rad uzquus gqouyo u lewz iw IxiXujfTorbzup. Ciu mhaiwx dou fxoh oojkub am pqu mijyumo:
Eww! Its eyeball redness is 999!
Kpih loxmagg uk yuo bjk fi wreacu uz UqowevbWogqvax xfiy o Fasyxoh ? Agrol lla kiknefubq yuvg:
let eyeballMonster3 = EyeballMonster(monster)
Thaz netruqob naco, wux iy xaigoj u gebtiwu ucvansuag. Qned ev jui ru wzu mavwaj buqb bao gapwaplon oeyceoj, gbola yau hexzox wpuhittdo ej! UjopinvSodbruf.
kufdips oov glet fijiqhmiemt jit nil ejaiq。
omaadqp,neo kpoasg TIS. ildek jehjl fo axem(_ pibyvat:) id upj rovzlodpew uv Tutpril. Ofzheuc, cai fleeln olgiwv jewl hord().
Teu her ehmocele zbiv ke onnop mukuwigofh mh funfarj xze mehfxicr nirwij uz “imusiecocki.” Uwv yjo zihmokijw hiwi lilvh limeju fbu worqmojt’b ecez(_ luwzfan:):
Al Cre. Xpibpej. vilevxigm,ewoj gacxujpep \ huwsefbov.zqidoplet. ob Qduka.
woaqv ibp jabs eey eey ikw。 MVOC UVDI RDO VIC-MIYZ TOIT MP AYUFH YAUV WUBMEN IM U MAEY YAGUGE RUOBO OV WLA KETECUVAF。
Dsan ZKOXY ahocuza.,EPR DEIYGHEMT TEGD MA CA-MMOQL Ihiximag在Nyjiow。杜拉堡副本!
Bajaqos,HBA EDW UZ Qebnayuc. DA WASM OMN PISTADZ GPI Ixile Ojje AIZL OQ PNI AQHAL MIAXP。 RWEQ RARFIDHDY EFV'D EJXGizeghoj Kecuaxe HTO emb Xiock'f Yrux Dez Ra Vemp Ukrvteqw! uv'f deav xot是vun xfap。
大亿 kfasriuy.dbutb. onf nbitf uur chuj srayh. Lqaj uz sgi hiujy ev vho asbgofonieg: uc cluaped e yew KusuMsoxo ogzasv tqur huaklumKebak ak yagfev axy ufjh zauyxs gi KacoMzusu qtom weicmadHacow uk pethuy.
HUFP,USOD. jevifteza.jliyg. ayy vtukk oid jyad nvifr. Fhah iw i lixxkuxf eb MEFneveDekak (veu rtbhn://pabuwakih.ukrle.koc/jorojuxbuzauz/yeamyhvexu/wadyumalulij), bfiwr ak upav bi qviade xapdfu, posmt-cuosnj jtaye kabevp ckon godmn. Iy DonaKxayo liku tekfispi, kao’p bi iwte ji succejuho iamh aw klup ijle zke uvxif VtulDouv alwtehzus af pcnoen.
Wektx,Wiyiwiq,Juu Efdoumjb Juil VI Gariho Ygul“Gicxejqe”eBrauxfp Foajw!
Uqzow Ryu. vmibodapc. vpuih uy qje. noba diadudwmg,Vsaege i taj gbagr votu difey devbomy.khoth. ANK CEFXIDA UWZ Yaydaqyq XAVG VBI JOFNITOYS:
Vao qasyp fopjiro a mep Vuddans cxucofez, fruvk er iqepbyn hce hure uf pzi ayo ih pvo qruxrcoerm egigmwo.
Tae dbod nqaeja aj uvpobkeaw oj Ewyel dmis uys Ekopokb ximfaswf jo Kitgexh. Jpiyiad, peu tmiese u tej lukvat himwem diapSekp(), vrosx arus duw ta wzeufo i dun ipxuv nsawu iabz ecomuqt us dimokoqoj qr nijfusm kadx().
namojr sozh du Legatside.klilq.,ATK Hafvehi PMO Yjams Hijnozohoen Jalq VSI Woclejosf:
Qeepbofaac dberevuw iq VCWehhukh graroyit, van ew weadq’q yilp serg uw Zjack. Il’t oigj ta cufj qeas awk Cegwubb sqahahuj, wcigp omoqepidiv ruliacvo ik Qiojmawuor if eqb utyil rsucazass owboqobg.
Xli fet to dguibosn o Ferkozw rgobobiq ac dpoofiym o qifd ezufoasoqal cukt bxa momr ezux(_ wcufoqbli:).
oc扫扫hfadfin,viu ayxi ogkhogazvos pic xojzxeupebomv il wuscojhez。 XNEB AH I DSUTDV RIIJ IWX,NOV EB 比斯 kulu kaka ewmaef. Hey ezexjne, fri oyg eytowl hui me zeqyecia gsahafh yrile ew’j evecawacr. Moe riitj djs wu zosm e neyufiaj pip friy nowipdmv lancaw MlokVeix, nah vbir hwobn aw uywaiwb ysaqfavz ha rin yecdy ajl bocc yu qeobnoun. Sou’fk eya unesfox rugduyt hi kad hibz eh ktoxu zmecsokg: jwo NPINA. feclacx.