Skip to content

Instantly share code, notes, and snippets.

@ignazioc
Created November 28, 2017 19:59
Show Gist options
  • Save ignazioc/8dad0fbcf3e83786ca0d35407b422d11 to your computer and use it in GitHub Desktop.
Save ignazioc/8dad0fbcf3e83786ca0d35407b422d11 to your computer and use it in GitHub Desktop.
//: Playground - noun: a place where people can play
import UIKit
//Everything starts with defining a protocol
protocol Logger {
func log(_ mex: String)
}
//This is one implementation of the protocol
class LocalLogger: Logger {
func log(_ mex: String) {
print(mex)
}
}
//We can define one protocol that all the objects that need a logger can implement
protocol HasLogger {
var logger: Logger { get }
}
//Who needs a logger doesn't need to do anything because the HasLogger protocol
//has one default implementation
extension HasLogger {
var logger: Logger {
return LocalLogger()
}
}
//this is the class that need a logger, we just make the class implement the protocol.
class ObjectWithDependencies: HasLogger {
func doSomething() {
self.logger.log("Now I can use a logger")
}
}
ObjectWithDependencies().doSomething()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment