Skip to content

Instantly share code, notes, and snippets.

@oleksii-demedetskyi
Last active December 12, 2020 05:04
Show Gist options
  • Save oleksii-demedetskyi/6b72a7805034ba69effc to your computer and use it in GitHub Desktop.
Save oleksii-demedetskyi/6b72a7805034ba69effc to your computer and use it in GitHub Desktop.
Service locator in swift
//: Playground - noun: a place where people can play
import UIKit
var str = "Hello, playground"
class ServiceLocator {
private var registry : [String: Any] = [:]
func registerService<T>(service: T) {
let key = "\(T.self)"
registry[key] = service
}
func tryGetService<T>() -> T? {
let key = "\(T.self)"
return registry[key] as? T
}
func getService<T>() -> T {
let key = "\(T.self)"
return registry[key] as! T
}
}
let locator = ServiceLocator()
protocol Cat {
func meow() -> String
}
protocol Dog {
func bark() -> String
}
class Murzik : Cat {
func meow() -> String {
return "Meeooow"
}
}
class Muhtar : Dog {
func bark() -> String {
return "Woof"
}
}
locator.registerService(Murzik() as Cat)
locator.registerService(Muhtar() as Dog)
let cat : Cat? = locator.tryGetService()
let dog : Dog = locator.getService()
cat?.meow()
dog.bark()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment