Advertisement
Revolucent

Swift Service Resolver

Jan 7th, 2016
555
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 1.37 KB | None | 0 0
  1. // Paste this code into a Swift playground.
  2.  
  3. // @objc is required for this to work
  4. // Try removing @objc and see what happens.
  5. @objc protocol ServiceType {
  6.     func performService() -> String
  7. }
  8.  
  9. class ServiceResolver {
  10.     private init() {}
  11.    
  12.     private static var services = [String: Any]()
  13.    
  14.     static func resolve<R>(proto: Protocol) -> R {
  15.         return services[NSStringFromProtocol(proto)]! as! R
  16.     }
  17.    
  18.     static func register(proto: Protocol, instance: Any) {
  19.         // NSStringFromProtocol works ONLY with Objective-C protocols.
  20.         services[NSStringFromProtocol(proto)] = instance
  21.     }
  22. }
  23.  
  24. // To conform to an @objc protocol,
  25. // a class must descend from NSObject
  26. class Service: NSObject, ServiceType {
  27.     func performService() -> String {
  28.         return "I'm doing it!"
  29.     }
  30. }
  31.  
  32. // To conform to an @objc protocol,
  33. // a class must descend from NSObject
  34. class MockService: NSObject, ServiceType {
  35.     func performService() -> String {
  36.         return "I'm mocking you!"
  37.     }
  38. }
  39.  
  40. // .self is required here due to a pecularity of Swift. If there's more than one parameter,
  41. // you have to use .self
  42. ServiceResolver.register(ServiceType.self, instance: MockService())
  43. // We don't need .self here because there's only one parameter, though
  44. // you can add it if you wish.
  45. let service: ServiceType = ServiceResolver.resolve(ServiceType)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement