Skip to content

Instantly share code, notes, and snippets.

@shanev
Last active February 23, 2018 20:09
Show Gist options
  • Save shanev/c24ca021ffd35d6cfba37f94111c69e4 to your computer and use it in GitHub Desktop.
Save shanev/c24ca021ffd35d6cfba37f94111c69e4 to your computer and use it in GitHub Desktop.
Generic view controllers with storyboards and view model injection
struct CustomViewModel {
let data: String
init(data: String) {
self.data = data
}
}
final class CustomViewController: ViewController<CustomViewModel> {
override func viewDidLoad() {
super.viewDidLoad()
print(viewModel.data)
}
}
// Delete @UIApplicationMain from AppDelegate
// Add the following main.swift file
import UIKit
// reference each view controller before UIApplicationMain runs
// can be automated with Sourcery or SwiftGen
print(CustomViewController.self)
// The following is required because there's an impedence mismatch between
// `CommandLine` and `UIApplicationMain` <rdar://problem/25693546>.
let argv = UnsafeMutableRawPointer(CommandLine.unsafeArgv).bindMemory(
to: UnsafeMutablePointer<Int8>.self,
capacity: Int(CommandLine.argc)
)
UIApplicationMain(CommandLine.argc, argv, nil, NSStringFromClass(AppDelegate.self))
let viewController = CustomViewController()
//viewController.viewDidLoad() // assertion failure
// usually in prepare(for segue: UIStoryboardSegue, sender: Any?)
// compiler suggests the correct type: CustomViewModel
viewController.viewModel = CustomViewModel(data: "hello")
viewController.viewDidLoad() // hello
import UIKit
public class ViewController<T>: UIViewController {
var viewModel: T!
override public func viewDidLoad() {
super.viewDidLoad()
assertViewModel()
}
}
private extension ViewController {
func assertViewModel() {
assert(viewModel != nil)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment