Last active
February 23, 2018 20:09
-
-
Save shanev/c24ca021ffd35d6cfba37f94111c69e4 to your computer and use it in GitHub Desktop.
Generic view controllers with storyboards and view model injection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct CustomViewModel { | |
let data: String | |
init(data: String) { | |
self.data = data | |
} | |
} | |
final class CustomViewController: ViewController<CustomViewModel> { | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
print(viewModel.data) | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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)) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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