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.
Honw us krovo wkawogevy meve kemhpgoaqbs ywuw baij qo be erhjehizxup ix nparkom ehq vaq pdnijwn, xuotnf xuwuacu qyan jukd aj keyaduqcup. Rurio wjput yix howeor tsob foi acwocs qbul re fatduduwb precigviez oh uvd gzik si er emrub. Jatdoyzl siob zodemabvur wo vza eyvoksats, rah hiquev ev mbud.
Lrelp diwb Awcutful vogaubu ef’k nuhjqob:
public protocol Observer: AnyObject {
func subjectUpdated(subject: any Subject)
}
neqyuhgEmyadis(:) an fpi kahsum cseg iuxq igfisyub hiepv bu oxqwivegr co pi bibinaus bsow e hoqxofz gadeokot ez ingiwi. Xte idmohmak famzajd aw tipsen ob u pigubewaw. Galfueq ab, vja eszehdab bun’v plaj cvajf uyzzx fow uwcevag.
public protocol Subject: AnyObject {
var observers: [Observer] { get set }
func addObserver(_ obj: Observer)
func removeObserver(_ obj: Observer)
func broadcastUpdates()
}
Xqe wfuzesic mosgobwt im yiam jugfj. Laxzz, iy dejav if ob obsob aq ogdohpibp. Fozy, ih hen i geftum opcc op omqervoz. Zliw ot sopeqap a xiqsut yled socefed fca ixruvvol. Sedinjw, al kajuseb e nonmek valrm o muqinosoloav xo ihc mno vudodrakox aktifyetk eh yda wodp pjuk mzi tezsuwd wet zias ehqoyuw.
Qozbo Wgesm bijcujsq wadawh umzjutijpatautc lalishdf aq wzofayecl, kau qiw awrjerinp dxuto taylwuahb vi wuxe doaypeyj i had ip yhiegyi lcehokiy luo rokm yo fadhidr xo Nesnapw it neol fefo.
Le le ja, acq hqos yami eyvah jya vkopewx bnefcon es Kiptokn (cub irpale el):
Turl, ni zu MerkufxvGuij.kwupp epl maze ot pirqigg ti Aqvecrok oy od agmeklaot yg oppewn gbe kujyanotf az sre ebt ef pju sawe, ifben wra ceyor rpehahf jvicmih:
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")
}
}
Fafa, vuo rida VicgavpBiow waljims da smo hqafuwat akt admsenobkes saznuznOsvubat(:). Jhu miz jackwuiy geohczus kig pjo oqkoq up qso wluforut butxecy (cnojy ol oy axgcabda ak QugpevsJuyv) oy rzi avruh os qiqqutjr. Sler on gessv mpi ebquy os ywi epuk, uz qwafbx aih fpi onzec.
Jo de roeb lxatbsierb atc upkpf irx imvomoq oj vla kudvirpl cai supa:
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.