Skip to content

Instantly share code, notes, and snippets.

@cipolleschi
Last active April 18, 2020 19:29
Show Gist options
  • Select an option

  • Save cipolleschi/698226d5238f082d63179b313a95398b to your computer and use it in GitHub Desktop.

Select an option

Save cipolleschi/698226d5238f082d63179b313a95398b to your computer and use it in GitHub Desktop.
Using protocols for dependency injection.
/// Protocol definition for the FileManager
protocol AppFileManager {
func contents(atPath: String)
}
/// Protocol conformance of the system FileManager
extension FileManager: AppFileManager {}
/// ViewController
class MyViewController: UIViewController {
var myPath: String
var content: [MyModel]
// ...
func loadContent(
fileManager: AppFileManager,
path: String,
jsonDecoder: JSONDecoder = JSONDecoder()
) throws {
let data = fileManager.contents(atPath: path),
self.content = try jsonDecoder.decode([MyModel].self, from data)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment