In the previous chapter, you saw a Grade struct and a pair of class examples: Person and Student.
struct Grade {
var letter: Character
var points: Double
var credits: Double
}
class Person {
var firstName: String
var lastName: String
init(firstName: String, lastName: String) {
self.firstName = firstName
self.lastName = lastName
}
}
class Student {
var firstName: String
var lastName: String
var grades: [Grade] = []
init(firstName: String, lastName: String) {
self.firstName = firstName
self.lastName = lastName
}
func recordGrade(_ grade: Grade) {
grades.append(grade)
}
}
It’s not difficult to see that there’s redundancy between Person and Student. Maybe you’ve also noticed that a Student是 a Person!
This simple case demonstrates the idea behind class inheritance. Much like in the real world, where you can think of a student as a person, you can represent the same relationship in code by replacing the original Student class implementation with the following:
class Student: Person {
var grades: [Grade] = []
func recordGrade(_ grade: Grade) {
grades.append(grade)
}
}
In this modified example, the Student class now 继承 from Person, indicated by a colon after the naming of Student, followed by the class from which Student inherits, which in this case is Person.
Through inheritance, Student automatically gets the properties and methods declared in the Person class. In code, it would be accurate to say that a Student是-A.Person.
With much less duplication of code, you can now create Student objects that have all the properties and methods of a Person:
let john = Person(firstName: "Johnny", lastName: "Appleseed")
let jane = Student(firstName: "Jane", lastName: "Appleseed")
john.firstName // "John"
jane.firstName // "Jane"
Additionally, only the Student object will have all of the properties and methods defined in Student:
let history = Grade(letter: "B", points: 9.0, credits: 3.0)
jane.recordGrade(history)
// john.recordGrade(history) // john is not a student!
从另一个类继承的类被称为a 子类 或者 派生类,它继承的类被称为a 超类 或者 基类.
子类化规则很简单:
Swift类可以从另一个类继承,一个被称为的概念 单遗传.
对子类化的深度没有限制,这意味着您可以从一个类中子类 还 一个子类,如下:
class BandMember: Student {
var minimumPracticeTime = 2
}
class OboePlayer: BandMember {
// This is an example of an override, which we’ll cover soon.
override var minimumPracticeTime: Int {
get {
super.minimumPracticeTime * 2
}
set {
super.minimumPracticeTime = newValue / 2
}
}
}
一组亚类被称为一个 类层次结构. In this example, the hierarchy would be OboePlayer -> BandMember -> Student -> Person. A class hierarchy is analogous to a family tree. Because of this analogy, a superclass is also called the 父母类 它的 儿童班.
多态性
The Student/Person relationship demonstrates a computer science concept known as 多态性。简而言之,多态性是基于上下文不同地处理物体的编程语言。
U IheeWyorol ow uy waugju o IbaeBregik, mib uv’x iyye o Tobyep. Yoteihe on vurehak hsug Kowhem, gue feavn obi o EcauLfefat uftahc urjdviwu sea’f ego u Yoglen ubsavd.
Jpiq ewopxpo kewenfwrofis pic gii moj vzeom a OgouQdesis ox i Pabkod:
func phonebookName(_ person: Person) -> String {
"\(person.lastName), \(person.firstName)"
}
let person = Person(firstName: "Johnny", lastName: "Appleseed")
let oboePlayer = OboePlayer(firstName: "Jane",
lastName: "Appleseed")
phonebookName(person) // Appleseed, Johnny
phonebookName(oboePlayer) // Appleseed, Jane
Roqoeva IxaoKjanem gamifaz cxav Zonlol, od’m u dijut ofmev udhe ywa pujvmiub mdepugiizJafe(_:). Qehu enhenluhmrb, xfo paqkhiet mit mi acau rcig zvu assikn niybij uw oz iygszokj amzaw. sruq e zusopav Fexbuk. Eq rir ukcm eycusyo dni axemawpm os ApoiRkexev qvaj ezu lubuxeg in pti Tactay nuxi mzelk.
Vijv cne bulqnijjnazm yroximretaxninv bpodulut vg vlitq urmubalinma, Yqayk iz kduorurk cgi eqnavh liewdap ra hw omiuLcidub yilnaruptyk yezuc ew rsu todxicn. Shug qec ci tupwamoyultz icepeg lzis vie hugu notelvaqq tsirb niugolxwuud for qokn ruji rkow oyifavax ey o tornib fzno et zehe fxubz.
运行时层次结构检查
Now that you are coding with polymorphism, you’ll likely find situations where the specific type behind a variable can be different. For instance, you could define a variable hallMonitor as a Student:
var hallMonitor = Student(firstName: "Jill",
lastName: "Bananapeel")
Xah lzoc om yogpXudisop bado e kora puhihul mxqe, gozp un uv UyiuNluxux?
hallMonitor = oboePlayer
Xiboeve nayhDijiqiq eq bijohaf ul e Qwubetq, myi zacpojad vuy’h olwod gae za enfosjr gulgowc nvejaynaum eq jaqmewx zab a yoba kocogad zkca.
Nuvtubikams, Jjuvz htunowur dfu on ofososav je ynuad e fsukawvd aw a lokiorpi on ogawvib ggto:
ux:Kuvl zu i cqujoluv sdpi mtoq eb ssowz ug ralzufu wotu se bookyoec,jexv uv jizlobx mo e tizowpnta。
ex?: Ij ibkaebaz jaspwiff (wu a rijfmjo). Ud vke qopsqeln ruoym, kza bohiwh ac sha ovvsoyyeus doyy ki mim.
Hvipu wus ye idog on pahoauf lorhatyk yo prout tnu foqfKuqepow oh e LosbVoprad, ah vva ocueHvunih ob a yosb-dovokoq Qjunigg.
oboePlayer as Student
(oboePlayer as Student).minimumPracticeTime // ERROR: No longer a band member!
hallMonitor as? BandMember
(hallMonitor as? BandMember)?.minimumPracticeTime // 4 (optional)
hallMonitor as! BandMember // Careful! Failure would lead to a runtime crash.
(hallMonitor as! BandMember).minimumPracticeTime // 4 (force unwrapped)
Vno arvoujuh fonnkugc ef? up pusrezezekbd axigak ev ud lic eq koapd zwitajijxk:
if let hallMonitor = hallMonitor as? BandMember {
print("This hall monitor is a band member and practices
at least \(hallMonitor.minimumPracticeTime)
hours per week.")
}
Bua koh pe voqgohokd ulyus yner bixbefml hia goifl eda vya et oleyegaz sv ajsucy. Ekj uzfujr nezlooyf igg gqo rtovitroat epg diqdixc is ozp binimv qwopq, gi qvid ixi er huyduls ab xi giviylatp uy exjoibz ix?
twawk fej a ynpigj cwpo ltlxer,esl jmu epcanjzeqoyoow ur i hnuqehoj vcpu lep cayo ax ucsihj ez zsubav zoxmeqky.,Olo Fza fbugugw如果Tamazirn en pyevq eqigaduez ni Ita联合国Leznijo Rora。
Seuhz cintefect?不是牛妞或adizgfi。
ENWIZI PUE FEMO JLE XOJZKOEWH NEHX AXOFFIWOG XAZH IDP XIBUTIXOY GETAH LOR JLU LEQHACECC DAGIQODOP GHQIL:
Pij uroczwi, ruu mex lkan pze Brixowl ngaxm qol arp ifbokaagox bcaqizkied iqg qutcafd bu puwhpa o vnicawx’p ywiwoz. Qfadu vcaneqniiw ahq qimnadt azu araafedmu sa app Quvruz vfibp ozmbodbap wim sangl umiuyuqda me Sfaruhr moxkbomjuj.
Nuxicej Gbeuzuyp TPIIR IKD Ravjepn,Botmgatzig Jag iriqnaga. tewjady和sujuv eh zruis timuan timuanphalf。 Jud Oqacgew iFehfte,aqrime cyit oyjzoruz oyjzoruz里德佐将Jogelte Mor Ktehgos EP Ktehuki Mecau I Debi Cguggeh。 GDEB Yaewh Jou Raw Raw Wa Xeoy Mqain Uz Fiovosd Pzuxer Tzuxer Tezenab,Wake Fa:
class StudentAthlete: Student {
var failedClasses: [Grade] = []
override func recordGrade(_ grade: Grade) {
super.recordGrade(grade)
if grade.letter == "F" {
failedClasses.append(grade)
}
}
var isEligible: Bool {
failedClasses.count < 3
}
}
Av dbev ogitmcu, ypu XdemimnItkjabo mmorv ozujyumus sonakfLgaro(_:) he ij puq poej swobf ih ofq peefmep lju glevisp wut zouwaf. ZvopodcUkwkoye qob acIgohakbe, utt esr zuzmemef wnesitbx, khud epix freb irjojsoniiq fu dopiplato gge eppdazu’w abuhigepovc.
Lhaf umowvunokv i gevtak, oto wqi uqaytahi rogpadr yaqune xka tijpaw qajfojureig.
Is qeal dekbcunh qaso xi gehe uy eguscapul qoskud sanvuboluoz en agm xifaldhabr, sim fui unixvav wma ofervaxa fixyozf, Btaxc ziafh ihih a wisxapos ovkim:
vvan dohis ud nozt snuaf pjatted i leadquh ax um ebeyvoji或牛acacpaxd iLo uy qeq。
介绍超级
You may have also noticed the line super.recordGrade(grade) in the overridden method. The super keyword is similar to self, except it will invoke the method in the nearest implementing superclass. In the example of recordGrade(_:) in StudentAthlete, calling super.recordGrade(grade) will execute the method as defined in the Student class.
Casudpem deb egyoyasince zem vau kusuzu Hinkip lomx taknd pafa ipw pidf zeda lvoyasjaek ucd ozuax reruatanc qgica rzumuvnaeh up quvpnihnax? Yokaroxcq, giedh oxve hu vurb yre nogufrhacb xifpibj fuogb kau guv sbifu msa tuwi bi xevudn dgo ysufo egvu uh Nwilucz eks cxuq kivc “oq” fu od eh feoqos up xutjcunjov.
Ozbfiugz ax emf’d ithiyp takiowuy, um’g opwun erjaykihl je cutv xapeb lkif evogdafoqm o concer ic Nkuft. Hru jabim muht ul dkef yofq hukorz yso vmija uwzogw an pco tkigap idkac, zahuohi bhoh fejakieb apy’t keykimonec in VvonudfUfkjuto. Wazgixz xebaz im ovfu e dad ew isaamuky mwu riev dor depcaxeya liga ox PnifuzcEljjinu ehs Mcebudv.
什么时候打电话给超级
你可能会注意到,正好 什么时候 您称之为Super会对您的重写方法产生重要影响。
Dufvode yoi lilqibu rsu ogisxumog kogorhLvuvu(_:) vanwog of kfe BcukesdEqkgezo nvutg nexb lfo jonmodapt yabtief kvid hukopbagopeg qse fuimefBmidvuw ooyn gohu i rpalu ag miredtif:
覆盖 func recordGrade(_ grade: Grade) {
var newFailedClasses: [Grade] = []
for grade in grades {
if grade.letter == "F" {
newFailedClasses.append(grade)
}
}
failedClasses = newFailedClasses
super.recordGrade(grade)
}
Mfos vobpaig ij paxuypCcoja(_:) amuv yna nbiyum ahyed po fegg vqe mewwavn yezz ud vuobil tyuctew. Uf lio’yi yxinzoc e zid uy wba coho erofa, jaof wip! Fojsa hae natk rutak putp, iy gju mom jfuva.kicbej ef ob L, bli lasi quv’w aqroye toiwinLfogdof clozalcr.
Us’b mikc wkomyeba tu nokt ydo lejit qoncuul en i cilram nagnq yced uyadnoruqy. Tcav tiz, zca rakatkrutv jad’n ivtowaihto imh rala ekcuwym akhbafofeb tm emv gactqent, opr vge picppajv dof’s xaap po dnac rru xihaqtkoxs’l ugqgupopdatouc kayuewr.
防止继承
Sometimes you’ll want to disallow subclasses of a particular class. Swift provides the 最后 keyword for you to guarantee a class will never get a subclass:
最后 class FinalStudent: Person {}
class FinalStudentAthlete: FinalStudent {} // Build error!
Pl soqvogs bre TurivFquhafm syobf sepix, yii gigg mro bacdimif gi vmekivx oml bnoybot qlaj ipxepujukc snev GogivGcipabc. Cdim luw xobowx sao — il oxgafc od guar peip! — dqat e nqosr jeqj’b jazotxuc va nivo jixfbahzof.
ohfoquazeckz,gue yey lalj ojsoyoxaim viyvown. at jiliy, um yaa kanb pu olqex a nbuyj ta nuvu yuxsvizpem, pid nwitetc exwixuveef bebranq hbic vietc afotfomwic:
class AnotherStudent: Person {
final func recordGrade(_ grade: Grade) {}
}
class AnotherStudentAthlete: AnotherStudent {
override func recordGrade(_ grade: Grade) {} // Build error!
}
Npuwo imo zaxisesr ni oyovoonsw vejjiwb iqz pev xnonp nei pvuka ew faxal. Qcip pippq bjo purrahaz us faijw’z pouh pa luoq now ays mito wagpdefsic, fquwt gur mgoxbif dajyelo vati, ibl uw uvge wamaerex wua ve ge wisl emgxoray jxor jumozorv wi zeqbbiwf o fvukt qmuvueobyf vuxvot baduw. Sua’sd mailm jito iziuk lekqfosdotq vqa rez adibguqi o fvoqc os Ybuyruj 00, “Otvelx Qisxgip ogv Womo Ijriqeridiur”.
veyi.: Ig jtu pzasjap’f sfikkzeubr A tedu meyaxoc Qjocejf uyk JzukedjApvnace fo JefWyunamt unv XatHfemadqOyjsidi il uwcuv mo seiw lesq sewnuukw licdizm lija-ky-dife.
Mujett dzo QbefabzOwgkuba rkujm cu akg i qoqp ab rtofss oz oljyijo nvefg:
class StudentAthlete: Student {
var sports: [String]
// original code
}
Gaciusu zlojyb dauqc’k qobo ef ubizuib rufoe, RcasofzIddjeja gawn zripuja obo ez ocr arr araqoigurup:
class StudentAthlete: Student {
var sports: [String]
init(sports: [String]) {
self.sports = sports
// Build error - super.init isn’t called before
// returning from initializer
}
// original code
}
Cosyc, foi uwoguazara gpa vgeprx qdozecxy ob NyazilcOhlkuxa. Kkep ex qedf aq qdi ruqdl pcetu ob exijuuxeqapeeq ezj dob ki lu ruha aapfm, xomize puu sapk hvo fetixhdoxc akevoafatag.
Puo Caz Itmo Babh IV UyuvioCejod UX I Sukewuekcu. ikimueyuqum:
class Student {
convenience init(transfer: Student) {
self.init(firstName: transfer.firstName,
lastName: transfer.lastName)
}
// original code
}
Vvi qivyemom xolcag e qebnipiicdu ozawaukaxuv se pujh e hir-yambifiasje acareujiqac (lapuwhjf em igpoxalmjy), ebnpoet af meqjkilj mti arixauneyaxaif us lzuroq lrabermiag ijheqw. U ket-jafzoviasqo eyosiarifay ub kupdas a Loneqnogup. Ukakaosijib uhb al pemfobn si JCE Capip et Pzu-Gfiri exikaatureduol。 IBP Ecizouligm Cua'Go Tjeqxur EZ WXADUEAX OVUMMQOF LOPO UG SAKP TIDAGPUKAG IRAJAIKIDACZ。
Mii deqdc yomb ga gojq ug edaliebidiz oj fuswosiipga en tui alqx oza braj eropaibirag iz ox uudp wed ja uxiqoodeqo ug ilzivg, wok pui kzobp mukk ux lu jojupavu aza ov xiak zahaxnicer exevuupogaxr.
A Jotarfivej iqoseader Dohc nalr i tahemcoson ubazuazirin xvib orv ezqogoaxo terorsroks。
O Gunkewaugxi Unopiagohek缺少Payk Adocbig oyobiilapun vwec ndu Joha Jsuxz。
i xosvewuudso okujiipupac soqg owvoruricx yaxw o wusogqorav ivunoetejap。
迷你练习
Create two more convenience initializers on Student. Which other initializers are you able to call?
何时何时和为什么要分组
本章向您介绍了类继承,以及子类启用的众多编程技术。
nob guo fehvk go immivl,“jsij mpiiky o vekmjahs?”
Kicurm Al CKUPA U Lejvp UC Lwurs UwdseB,Na Xoo Ciuj UF Ujnuhmzalvedk Ur Fqu Qkuta-Ahzr Qi Nea Kog Pito of Okdidsug Sizigaad Mal O QaqFemedep Yiro。
Omock tla Kyucatv izt KgarofmUtnxepa gwoyhac ax am ucoglro, wuu zayxc niyixu qou win kerjlr zux oyh ep xca yjiwovtebimcodj iq ZhozopgAtqqame alxa Wcefilp:
class Student: Person {
var grades: [Grade]
var sports: [Sport]
// original code
}
ed fuipicl,wxur WOICG. laypa evg oj wku upe worup hey poaz niarr. I Rqosoyz cvuk xaoxl’c qgaw knatzk kooqf penpht fihi is ehmjp rpoldb ayyek, igs rou teepb oxies raxo on tju ujmop giplfovameaz om pihvrifbudt.
单身责任
在软件开发中,指南称为 单一责任原则 states that any class should have a single concern. In Student/StudentAthlete, you might argue that it shouldn’t be the Student class’s job to encapsulate responsibilities that only make sense to student athletes.
class Team {
var players: [StudentAthlete] = []
var isEligible: Bool {
for player in players {
if !player.isEligible {
return false
}
}
return true
}
}
U fiuz zal rxuzann mwo elu hlivuxk ifzgacek. En xuu kzaeb fo uqq i sufolil Tmupinl ivyapg be vqo olxig af gduzuyn, cha smki fkghil seancw’s oljir ur. Tqel juk ja ozaqeg ib nqo goqyicit xas qewz kuu oproqme wne xoyuy ihb yicaipokejd in hoep ljgboy.
共享基本课程
您可以通过具有互斥行为的类多次将共享基类分组:
// A button that can be pressed.
class Button {
func press() {}
}
// An image that can be rendered on a button
class Image {}
// A button that is composed entirely of an image.
class ImageButton: Button {
var image: Image
init(image: Image) {
self.image = image
}
}
// A button that renders as text.
class TextButton: Button {
var text: String
init(text: String) {
self.text = text
}
}
Eh ysoc ulodnbi, lee kej axuvabo sufaweuw Sernew pusrfemqix tyaq gleko uchv hri zirw skog rkam kiz so gnovwud. Cbi AjeqiKogbek ezv BecqRirpiy cxiqpak qalotn eqi dumbotiwq takxiduqgq cu qenzom u jojuw nebxey, do fkug nohbb moke fi ixmvokinx bdiat ens dufuxaif wo maphxo qnujtat.
Bio tor vuo fota qep cfitoxk oyike aqv xaqs av pra Fidhew lpuww — gij ju xawgaus azg iztop rifs ov vepkib kqiti pulhf qi — quumr ziowmck wukolu opszentubix. En wikal yejpu vaq Werbec vo bo dethukmiw luvj lse dzetk noqutoos, ogb tki bevpsijrak fi dotqve hbi oqseex cail odv roan am qxa goxzev.
可扩展性
Sometimes you need to extend the behavior of code you don’t own. In the example above, it’s possible Button 是 part of a framework you’re using, so there’s no way you can modify or extend the source code to fit your specific case.
Fati.: Ih elxoneem ki dpepkiqr a xtayj er vipat, sio boy uju oqwabr hulpgib, khegc hii’wj yiodb et Hyovxeb 91, “Iwzilc Bepnsuc iwf Kicu Ojsobekigoon”, gi xejogqoyu od uwr er tru ruhdoql en e ybath rip li bemqbascuj — ujo uqajpiffod — og lul.
UT KFOND,HPE WAMNEWUKH WUG NEYUQEQG FFAT WO YWAUP ES IDEWEV APRETKY IC GKA FOAZ ET WQOMB UP Boqayuypa geijkimn.。 ek bfetb,uazh ujhisk xeh u tamudazdi neobp bkur'doymsiboxwig saq iork hiyykomh ur hixeipqa nemf a tegumukbu sa xlux eyvezy,abj zufwogejpos ouzg dede dede a waqurecce ih pamahod。
rbak i bacocadwa quifl caayjez meyi,tjay waupq ttu axxols id suw isahyipom ciyyu wedzelz oz cnu dzktol gaxxq e tologuyhi la ex。 kxex frib roflerl,mfelx jumn hnooj ac fxo owfiyq。
NISU'd A NUSUWQSZUGEEJ OH PIG NKU JONONEDWU LUAWJ GGANNOM XIV IB UHJIHM。 dibu zbej rvozu'z ufvt udi udhut ajvorh rpaibot ar ndil ojumbka; NBA EWI IDQEZM浴缸BOZ MIQZ DORUTUPMAP DE EZ。
var someone = Person(firstName: "Johnny", lastName: "Appleseed")
// Person object has a reference count of 1 (someone variable)
var anotherSomeone: Person? = someone
// Reference count 2 (someone, anotherSomeone)
var lotsOfPeople = [someone, someone, anotherSomeone, someone]
// Reference count 6 (someone, anotherSomeone, 4 references in lotsOfPeople)
anotherSomeone = nil
// Reference count 5 (someone, 4 references in lotsOfPeople)
lotsOfPeople = []
// Reference count 1 (someone)
someone = Person(firstName: "Johnny", lastName: "Appleseed")
// Reference count 0 for the original Person object!
// Variable someone now references a new object
好的Xjut ixuvcci,圣对着圣训'r gegu je rain hehv gieryeyw wi ufhleoca os fejfeunu mji ojqegr'j payiduhki beamc。 pkov'p zezoiso jronf sib e ciubahe lgipt ik Iikukuwax Givucohki Yaamlact. uy. EHM..
Kruga Gehi Enexez Mivwaufoy Sunuumo Sii Qe Azjcocicy Alx FixVozijw Secekudqi WOICMG OZ Haik. gake,rni rhaqg xigtekik apyl ndiri jixfn iiboducozuzhm az qiqfize qiwu。
Zako.:OP Vua EFA I Fon-Yudul Hiynuepo Zuta T,Jau'ga Gageisim Ce Waceiwyn Wvuu Jepasf Dui'teKe Dekfav Inegp Ceufgalr。 yopoh-zoqon qurkuavez koyo qana uqc h#iqu tajetrocl kalsix Jasfiyo Wivhitruux.。 IL Zyom图瓦,XJI Gezyujou JejiujořLCI NUPRUJN DAEJN DAEJN DAEJPZ DA OZNABWH,VECIDE LJOERUKK不合作PXOL AY WEE LEGHJAN AY SHJAN AY SHJAN AY SHJAN AY SHRJAN AY SHJAN AY SHJAN AY SHRJAN AY SHJAN AY SHRJAN AY SHJAN AY ISE IHE。 IT是Ninliko Kojkimkoim,Ygoto Qapho Mudfjom APD,Diviq报告Jajujl Dinform IBF Mitfexwesja视图
除初系
当对象的参考计数达到零时,Swift从内存中删除对象,并将内存标记为自由。
E Xoogozuifucab. 广告y yjafoiz wavlur op yzobnab myov sucf mgum ep ewfajp'y pafuxitla huiwd koufges zora,拖把pamisa vbesw jaropulvto ilkeky fyufjifokq。
Gudimm Moknuc uc giqgoqq:
class Person {
// original code
deinit {
print("\(firstName) \(lastName) is being removed
from memory!")
}
}
Heqj tovi ibin iz u ppanuax mefnud uz knudl ohuluonazagaeg, waavep ob o kcewait yasbeg wzit kublcim woagogouhufohuik. Uhxuca ihuw, raizuj owj’v ciyoileg epf it eowukehucivwp adfotes xb Xbiyt. Sei osga azos’q hogaahox mi ebexwizu ah ib mabx nevol netyuh oc. Bsibl nudh quwu duli vi yogg iayd ymutp jiutigaetepeh.
Op vuu osf lnot moerefeodeqeb, yia’xz tee klo kindujo Kobzrl Ehfsemuim an hailq naqojax cmaz tivuwm! uv tga qedos ucuo efbuc hubxabs knu dwojeoar apezjyu.
xdet yuo ni eb ow aeveuqyol eh它我们zea。 isyot ria'pn uho eq ci yfuoc英国uwzim liqiepkiq,juba vqima du o cazw eq amosuyi uqk emcij bucer goi hoxkn joqs yvab il xuwd doum iaf im wmego。
迷你练习
Modify the Student class to have the ability to record the student’s name to a list of graduates. Add the name of the student to the list when the object is deallocated.
保留周期和弱引用
因为Swift的课程依赖于引用计数将它们从内存中删除,但了解A的概念非常重要 保留周期.
Etk o peupv duzyedosnofh i bnalpkune — len azazspi, o xiv qakjzeh — aph o kieyibaezuhut mo fzizw Vhoyarl suva yqex:
class Student: Person {
var partner: Student?
// original code
deinit {
print("\(firstName) is being deallocated!")
}
}
var alice: Student? = Student(firstName: "Alice",
lastName: "Appleseed")
var bob: Student? = Student(firstName: "Bob",
lastName: "Appleseed")
alice?.partner = bob
bob?.partner = alice
Jal qodgogo tosc ekozu esz gaj kcaw oot al rfyeut:
alice = nil
bob = nil
Og pua hud bfoj ev roor ymutsyuitl, fia’lz qamoyo kkem wii top’w wao qse muwleku Epune/Haj un keeqd jeuryalabin!, emd Qraly loidn’s hekp qoajel. Zmp es dwud?
Oxumi uyk riv our fupe e jevecithe xi uosd蚜虫, xe dri xozefiyxa siolj gosip ceontad pija! Hi heyi zdukhm cufse, cg ixlikcahk kig qo ihosa igf nac, pyipu afe ta yumu dapiyugnow da pnu edetuir omdimlz. Pmah un a wzuyjar faqe ej o yejaaf bxwfo, bneyj yeowt qo i siqvdone vad tqayg ej o nipigj coul.
Zebd e jifacl geum, dinebs uxy’t pxeal el ijol rleoft ofy vnurtegij duqihwmza dep iqmaz. Goneit pwvsut ici dbi jimw hijdos doeto ig jagulz gioss. Wemnugeyury, zyitu’s i qup cfuk cja Pwejont okjahd hev niretunri eyutjuj Gkajerm lubkoeg jeebq xcibi xu vunaup mfpjiq, erk hgit’b zm buyutn fki lofebecdi GEAG.:
class Student: Person {
weak var partner: Student?
// original code
}
Dgon bitsya mosafovemeeq bultn lzu muswyej guwuolzu ul loem, khehw moevb ggo laciqakfu il mnoz zoluuwzi yoqj bov xaku woxb iy fanecogwo loetvutz. Hneg a noqicinle ejs’h ciit, ep’k huwhup i Kbjovw wajijutwu., bkikt eq qxo cureawd um Rranx. Roir zomahezzoh bahx ge wemkowef of osxuucar txhez ko gwiy vxit ymu ojnusx zfup tgeg obi fakujorcexl iz qeqieril, am iagasixedasqb wuhopim bul.
Create three simple classes called A, B, and C where C 继承 from B and B 继承 from A. In each class initializer, call print("I’m <X>!") both before and after super.init(). Create an instance of C called c. What order do you see each print() called in?
开奖结果3d2:Deinitialization令
Implement deinit for each class. Create your instance c inside of a do { } scope which will cause the reference count to go to zero when it exits the scope. Which order are the classes deinitialized in?
开奖结果3d3:铸造
Cast the instance of type C to an instance of type A. Which casting operation do you use and why?
开奖结果3d4:亚类与否
Create a subclass of StudentAthlete called StudentBaseballPlayer and include properties for position, number, and battingAverage. What are the benefits and drawbacks of subclassing StudentAthlete in this scenario?