Skip to content

Instantly share code, notes, and snippets.

@aprofromindia
Created December 20, 2019 12:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aprofromindia/c6082a37246236e8c2e1b85612e1a58d to your computer and use it in GitHub Desktop.
Save aprofromindia/c6082a37246236e8c2e1b85612e1a58d to your computer and use it in GitHub Desktop.
Observable, Subscriber Protocols and Extensions in Swift
//
// ObserverProtocols.swift
//
// Created by Apro on 18/12/19.
//
import Foundation
protocol Subscriber: class, Hashable {
associatedtype State
associatedtype Observable
var state: State { get set }
var observable: Observable { get set }
func update(state: State)
}
protocol Observable: class {
associatedtype Subscriber: Hashable
var subscribers: Set<Subscriber> { get set }
func add(subscriber: Subscriber)
func remove(subscriber: Subscriber)
}
extension Observable {
func add(subscriber: Subscriber) {
subscribers.insert(subscriber)
}
func remove(subscriber: Subscriber) {
subscribers.remove(subscriber)
}
}
extension Subscriber where State == Int {
func update(state: Int) {
self.state = state
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment