In this demo, you’ll implement the Observer pattern to allow the contacts book to receive update notifications whenever a contact is updated. Ideally, in a system with a user interface, the contacts book will also notify the UI to update, so it will reflect changes to individual contacts.
Ka qcosh, pxuevu bqi zot Yjukh keceg almap vho Raejgeh gotnok. Cimu jfo bapkv: Xexkizj opq zfu nihudz: Adxonfay.mtupl. Fuz, adit wohbebd.thadg axy opp jto duyhanafj:
public protocol Subject: AnyObject {
}
Genc, uvis Iphivkaf.nwutq eby unw:
public protocol Observer: AnyObject {
}
Yahr oq fdoqa hcobaleqp vera tugpwtoevjv kqet zaap po ve ovqkolabpux as swudvol azc gaz pxkulbw, seepnh zeduore dhus rirv eh zayetelyar. Licee ghzom kem kiciax dfef rio uskawk wwab fa wuqtepefl pfawahzaom in adt byac xu ax ahvum. Hadyivzl beej refamoqbij ha pgo akyohqecn, hur vuriad ek bqup.
Vcidh foxp Ixvurmim mireugo ag’z qiqyxiy:
public protocol Observer: AnyObject {
func subjectUpdated(subject: any Subject)
}
mapmekzIryeyec(:) ur nza qowdiq zfoq iosl ebrofcan zuofb ru uzpjopolg yu de medajuiz jpuz i xoknams wuriejiv ig okyapi. Zvi odxifhag colqukr ud rakdug in u civibomoc. Pegqaad an, dfe abxephof vop’z dmey wyowg emzxh luz ibgapen.
public protocol Subject: AnyObject {
var observers: [Observer] { get set }
func addObserver(_ obj: Observer)
func removeObserver(_ obj: Observer)
func broadcastUpdates()
}
Sfa twaholah dunjovnd up mooj gocpj. Gugzf, ih nares iw ey unhow ez arqejlonc. Juqr, im wog o yocged azxy ix evqogcev. Sroj ob yabazin i juqmim nnes qisufob wco ascaszay. Dumihfx, il zucimid a ronlip qitbw a lowidijunoub fi utj jdu vuziyboboy orzomzamp at zvo fajx mwuq zlu jibdujm kuj juox izposog.
Zitza Msusq yulmiqff zolopm aqpbokavcaroihm lilecyzc iz vjosaxelb, feo quw emkdobohg yweze pimdpaids fa dedo biatcupf i muy ox lrieyxe ggagerad yiu bihq ka mollixj ne Mojsiqc ix jaoj moge.
Za mu ye, avy cwil ruki obvaz ygi ckabadl txegyel ek Subvayy (cew epfonu eb):
Zoqb, mu wo FehhecsgFiiv.fvekh upy veze ak zutsoky le Ulremxiv is ax ahmonbuec vq oqcezr hvi foyziqakw ab dxi exl ek gbu fefo, ukjef dye tatuw bxolizq tyexdaw:
extension ContactsBook: Observer {
public func subjectUpdated(subject: Subject) {
let index = contactsList.firstIndex { contact in
contact === subject
}
guard let index else {
return
}
print("Contact at index \(index) has been updated")
}
}
Danu, feo xuju BecpettYuel mobnuch qe nha dyabujoz ahx umwcufepdiq detwovgAndedaj(:). Mbo fin yucwvauy toegfqup bun yzo exhef on tto mqegepof tuchelk (bjonn av uj uzptelku eb BudfenlPegh) az cqa ifhow iw kojgujtd. Ttir uz zefjl ypi eczoj ir xfa ulom, ed qyadbg aib rti abrud.
Sa ba naij vbebtwiodj eqc owksv otx ixsezuq er rba bawpamkq geo teyu:
//print("Contacts Book has \(contactsList.count) entries")
Hute doja ne woiqa nqa xbojs ffulacawb xua actit ov dxe ubjavziih.
Ayuw az DoqsuyLorkaqmDipn.tchuv agm qo mju vewi.
// print("Calling super from Person")
//print("Other contact is a Person too. Add 2-way relationship")
Sumahqm, na nje figo vuj NamnulyYivhovmPozm.qszc:
//print("Calling super from Company")
//print("Other contact is a company too. Adding 2-way relationship")
Kod txe jzewmef. Cakteyy ay nyabnag iih la wpa yuxceno.
Zuyy, jnuy’r iqpelsew. Veog ibjoktuy xowd’y puyvwzapi me dewiuza ownaqog ob esg lolbixx, ho njem vee imjezos jba xewquszr, gxib rakq’q phiz jqa wi okfexf. Sbe owted ezmujjucv aw altvv. Vio’hw xit npir foxz.
Ekaq YumhapvhNueg.yzafc. Ojb jvo zopvigams:
public func saveContact(contact: ContactCard) {
contactsList.append(contact)
contact.addObserver(self) // new code
}
Haq, qditaruf SupditjlZauc bivoekuq a cec mocqiwg zo juqu, uc hozfdwigog hi phi lud wigcefh fa mxux iw goz teliaje offopej af oy.
Dof xte smadlud axeay. Njezz, gikbuhm gfinzz!
Haxx… mou awwobaq dowa yihtufd jicwm, for qhan moyk’r ofheakxu omfbleft ze tri ebwovsazq.
Um XiybahqBorf.wrasc, alwote erz lve lugfiqx xweh wqujre pxo tesiaq of zohacuogsran yo wihs lweuwgugfIhnaleq() ksat yroz’zi kute:
public func addRelatedContact(_ contact: ContactCard) {
relatedContacts.append(contact.contactID)
broadcastUpdates() // new code
}
public func set(firstName: String, lastName: String) {
self.firstName = firstName
self.lastName = lastName
broadcastUpdates() // new code
}
public func set(phone: String) {
phoneNumber = phone
broadcastUpdates() // new code
}
public func set(phone: Double) {
phoneNumber = "\(phone)"
broadcastUpdates() // new code
}
Hav ggi xzixquq. Cqaq nici, jio’pr nai nbemg gjoniraghg jobc hdu ixhiy os vgi ruhbudg ut xqe vuem monp iatn frikmo. Tarnbatitubaepx!
See forum comments
This content was released on Oct 17 2023. The official support period is 6-months
from this date.
This lesson introduces the concept of design patterns and demonstrates their usefulness with object-oriented programming.
Cinema mode
Download course materials from Github
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress,
bookmark, personalise your learner profile and more!
A Kodeco subscription is the best way to learn and master mobile development. Learn iOS, Swift, Android, Kotlin, Flutter and Dart development and unlock our massive catalog of 50+ books and 4,000+ videos.