By default didSet of a property don’t called during init, so we can use defer to fix that issue.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class VideoPlayerController: UIViewController {
enum State {
case idle
case loading(URL, Data)
case playing(Video)
}

var state = State.idle {
didSet { updateVideoView() }
}

init(state initialState: State) {
super.init(nibName: nil, bundle: nil)
// By deferring the state assignment, our property observer is
// invoked, so we don't need to call updateVideoView() manually.
defer { state = initialState }
}
}