Skip to content

Instantly share code, notes, and snippets.

@randomstep
Last active September 3, 2015 07:49
Show Gist options
  • Save randomstep/e7a6263a1f4b3a993cf9 to your computer and use it in GitHub Desktop.
Save randomstep/e7a6263a1f4b3a993cf9 to your computer and use it in GitHub Desktop.
show simple dependency injection EDIT: Ok really just dependency inheritance
// do DI easy with protocol / extension?
class PostcardStore {
let postcards = ["France", "Romania"]
func calcPostage(from: String, to: String) -> Int {
return 42 // good enough until tests tell us otherwise
}
}
struct Context {
var notificationCenter = {
NSNotificationCenter.defaultCenter()
}
var locationManager = {
CLLocationManager()
}
}
protocol InjectableContext {
var postcardStore: PostcardStore { get }
var context: Context { get }
}
extension InjectableContext {
var postcardStore: PostcardStore {
return PostcardStore()
}
var context: Context {
return Context()
}
}
class Controller: InjectableContext {
// needs store!
func mailCards() {
let cards = postcardStore.postcards
let postage = postcardStore.calcPostage(cards.first!, to: cards.last!)
print(postage)
context.locationManager
}
}
let mainController = Controller()
mainController.mailCards() // should use DI so we can test
@randomstep
Copy link
Author

I like the idea of having small, well-formed dependencies that vend specific sets of functionality. I whipped this example up in class quickly, to prove the language concept. the example needs much better structure and naming. To take it further, could have an "Injector" that tests for protocol conformance and if so sets the various properties.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment