Skip to content

Instantly share code, notes, and snippets.

@kboy-silvergym
Last active December 22, 2017 08:45
Show Gist options
  • Save kboy-silvergym/c7496a0c0fa76d13dd008fda27f470f8 to your computer and use it in GitHub Desktop.
Save kboy-silvergym/c7496a0c0fa76d13dd008fda27f470f8 to your computer and use it in GitHub Desktop.
Easy Dependency Injection for Swift
protocol Repository {
func fetchInt() -> Int
}
class RepositoryImpl: Repository {
func fetchInt() -> Int {
// 通信する
let api = API()
return api.fetch()
}
}
class TestRepsisotry: Repository {
func fetchInt() -> Int {
// mockを返す
return 5
}
}
class UseCase {
let repository: RepositoryImpl = RepositoryImpl()
var testRepository: TestRepsisotry?
func inject(testRepository: TestRepsisotry){
self.testRepository = testRepository
}
func fetchString() -> String {
let number: Int
if let testRepository = testRepository {
number = testRepository.fetchInt()
} else {
number = repository.fetchInt()
}
let nuberString = String(number)
return nuberString
}
}
class UseCaseTest {
func testFetch(){
let testRepo = TestRepsisotry()
let useCase = UseCase()
useCase.inject(testRepository: testRepo)
let result = useCase.fetchString()
assert(result == "5")
}
}
struct API {
func fetch() -> Int {
return 5
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment