Skip to content

Instantly share code, notes, and snippets.

@sorin-ref
Last active December 5, 2018 18:50
Show Gist options
  • Save sorin-ref/ad1baca28e2e90da7649b7952d63eb80 to your computer and use it in GitHub Desktop.
Save sorin-ref/ad1baca28e2e90da7649b7952d63eb80 to your computer and use it in GitHub Desktop.
// 4. Service that weakly delegates input and output to a client that aggregates (i.e. references and uses) the service (instead of inheriting from it). Allows weak/unowned definition for the delegate reference on service side, ensuring no memory leaks would be caused (even if client side developers don't know about ARC). And through the use of an extension, default implementations may still be provided whenever needed (and when there is no delegate set at all, a fallback implementation can be defined by the service itself too).
public class Service4 {
public init() { }
public weak var delegate: Service4Delegate?
public func doSomething() {
if delegate?.input() ?? false {
delegate?.output(text: "done")
}
}
}
public protocol Service4Delegate: class {
func input() -> Bool
func output(text: String)
}
public extension Service4Delegate {
func output(text: String) -> Void {
print(type(of: self), text)
}
}
class Client4: Service4Delegate {
var service4 = Service4()
init() {
service4.delegate = self
}
func input() -> Bool {
return true
}
func doSomething() {
service4.doSomething()
}
}
Client4().doSomething() // prints "Client4 done"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment