Last active
February 17, 2020 03:00
-
-
Save zhouhao27/4014b5ed4bf0dfa9ca669ace863e53f7 to your computer and use it in GitHub Desktop.
A Swift-y Approach to Dependency Injection
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
// Refer to: https://danielhall.io/a-swift-y-approach-to-dependency-injection | |
// Part two: https://www.danielhall.io/swift-y-dependency-injection-part-two | |
import Foundation | |
protocol NetworkingInjected {} | |
extension NetworkingInjected { | |
var networking: NetworkingProtocol { | |
return NetworkInjector.injectNetworking() | |
} | |
} | |
protocol NetworkingProtocol { | |
func request() | |
} | |
class MyNetworkingManager: NetworkingProtocol { | |
func request() { | |
} | |
} | |
class HisNetworkingManager: NetworkingProtocol { | |
func request() { | |
} | |
} | |
struct NetworkInjector { | |
static func injectNetworking() -> NetworkingProtocol { | |
return MyNetworkingManager() // default | |
} | |
static func injectTestingNetworking() -> NetworkingProtocol { | |
return HisNetworkingManager() | |
} | |
// Method 1: Using property. Can set to different value during test later | |
// static var networking: NetworkingProtocol { | |
// return MyNetworkingManager() // default | |
// } | |
} | |
class MyViewModel: NetworkingInjected { | |
func getData() { | |
networking.request() | |
} | |
} | |
class TestCase: NetworkingInjected { | |
var networking: NetworkingProtocol { | |
return NetworkInjector.injectTestingNetworking() | |
} | |
func startTest() { | |
networking.request() | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment