Last active
December 12, 2020 05:04
-
-
Save oleksii-demedetskyi/6b72a7805034ba69effc to your computer and use it in GitHub Desktop.
Service locator in swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//: 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