Skip to content

Instantly share code, notes, and snippets.

@0xPr0xy
Created July 3, 2018 11:51
Show Gist options
  • Save 0xPr0xy/fa9ca9de1da37884e9fd9d762e87937c to your computer and use it in GitHub Desktop.
Save 0xPr0xy/fa9ca9de1da37884e9fd9d762e87937c to your computer and use it in GitHub Desktop.
composition over inheritance with viewcontroller lifecycle awareness
class UIViewControllerLifecycleBound: UIViewController {
public let lifecycleBindings = LifecycleBound()
init() {
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
lifecycleBindings.didLoad()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
lifecycleBindings.willAppear()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
lifecycleBindings.didAppear()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
lifecycleBindings.willDisappear()
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
lifecycleBindings.didDisappear()
}
}
class LifecycleBound {
typealias Code = () -> Void
enum State {
case didLoad
case willAppear
case didAppear
case willDisappear
case didDisappear
}
private var codeForState: [State: [Code]] = [
.didLoad: [],
.willAppear: [],
.didAppear: [],
.willDisappear: [],
.didDisappear: []
]
func register(code: @escaping Code, state: State) {
codeForState[state]?.append(code)
}
private func runCodeForState(_ state: State) {
codeForState[state]?.forEach({ code in
code()
})
}
func didLoad() {
runCodeForState(.didLoad)
}
func willAppear() {
runCodeForState(.willAppear)
}
func didAppear() {
runCodeForState(.didAppear)
}
func willDisappear() {
runCodeForState(.willDisappear)
}
func didDisappear() {
runCodeForState(.didDisappear)
}
}
class MyController: UIViewControllerLifecycleBound, BoundCode {
override init() {
super.init()
initialize()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initialize()
}
}
protocol BoundCode: class {
func initialize()
}
extension BoundCode where Self: UIViewControllerLifecycleBound {
func initialize() {
lifecycleBindings.register(code: {
print("hello world!")
}, state: .willAppear)
lifecycleBindings.register(code: {
print("bye world!")
}, state: .didDisappear)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment