Skip to content

Instantly share code, notes, and snippets.

@andredsp
Last active August 31, 2017 03:30
Show Gist options
  • Save andredsp/3243b480038190a861ef33b1a8b229eb to your computer and use it in GitHub Desktop.
Save andredsp/3243b480038190a861ef33b1a8b229eb to your computer and use it in GitHub Desktop.
Simple protocol to inject dependencies when `init(with:)` is not available (e.g. XIB and Storyboard UIViewControllers)
//
// Injectable.swift
//
// Created by André Pinto on 06/05/17.
// Copyright © 2017 André Pinto. All rights reserved.
//
protocol Injectable {
/// Type which defines the dependencies to be injected
///
/// e.g.:
///
/// typealias Dependencies = (detailURL: String, screenTitle: String, trackingId: Int?)a
associatedtype Dependencies
/// Instance with the injected dependencies
var d: Dependencies! { get set }
/// Dependency injector
mutating func inject(_ dependencies: Dependencies)
/// Assert that the dependencies are set.
///
/// The default implementation just checks if var `d` is not nil.
func assertDependencies()
}
// Default implementation of `inject()` and `assertDependencies()`.
extension Injectable {
mutating func inject(_ dependencies: Dependencies) {
d = dependencies
}
func assertDependencies() {
assert(d != nil, "Dependencies are empty!")
}
}
/* ** Instructions **
1. Conform to Injectable prototol:
class SomeViewController: UIViewController, Injectable {
2. Define the dependencies:
struct SomeDependencies {
let detailURL: String
let screenTitle: String
let trackingId: Int?
}
typealias Dependencies = SomeDependencies
var d: Dependencies!
3. Assert the dependencies (e.g. in viewDidLoad for UIViewControllers):
override func viewDidLoad() {
super.viewDidLoad()
assertDependencies()
}
4. Inject values after object is instantiated:
let deps = SomeViewController.Dependencies(detailURL: "http://host.com",
screenTitle: "Nice Title",
trackingId: 11)
someViewController.inject(deps)
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment