Skip to content

Instantly share code, notes, and snippets.

@starhoshi
Created January 12, 2017 16:47
Show Gist options
  • Save starhoshi/dd595da8e1a72b5938bfb9bb3c7b1a3a to your computer and use it in GitHub Desktop.
Save starhoshi/dd595da8e1a72b5938bfb9bb3c7b1a3a to your computer and use it in GitHub Desktop.
Swift observer pattern.
import Foundation
protocol Observer {
var id: String { get }
func update(_ string: String)
}
extension Observer {
func update(_ string: String) {
print("\(type(of: self)) に届いた新しい値は \(string) です。")
}
}
protocol Subject: class {
var observers: [Observer] { get set }
func add(_ observer: Observer)
func remove(_ observer: Observer)
func notify(newString: String)
}
extension Subject {
func add(_ observer: Observer) {
observers.append(observer)
}
func remove(_ observer: Observer) {
for (index, registerdObserver) in observers.enumerated() {
if registerdObserver.id == observer.id {
self.observers.remove(at: index)
}
}
}
func notify(newString: String){
print("新しい値 \(newString) を observer に通知します。")
observers.forEach { observer in
observer.update(newString)
}
}
}
final class SubjectA: Subject {
var observers: [Observer] = []
}
final class ObserverA: Observer {
var id = UUID().uuidString
}
final class ObserverB: Observer {
var id = UUID().uuidString
}
let subjectA = SubjectA()
let observerA = ObserverA()
let observerB = ObserverB()
subjectA.add(observerA)
subjectA.add(observerB)
subjectA.notify(newString: "New!")
subjectA.remove(observerB)
subjectA.notify(newString: "New!!!!!!!!!!!!!!!")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment