Skip to content

Instantly share code, notes, and snippets.

@n8chur
Created June 6, 2019 23:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save n8chur/4cf04fb0940002087b2832b67c6b7552 to your computer and use it in GitHub Desktop.
Save n8chur/4cf04fb0940002087b2832b67c6b7552 to your computer and use it in GitHub Desktop.
Demonstrates that SwiftUI (in it's initial beta form) is unable to properly handle diffing of class objects. The counter will not increment as you might expect it to.
import SwiftUI
import Combine
struct ContentView : View {
@ObjectBinding var viewModel: ViewModel
var body: some View {
CounterView(counter: viewModel.counter)
}
}
struct CounterView : View {
let counter: Counter
var body: some View {
Text("\(counter.index)")
}
}
// Changing this to struct fixes the issue.
class Counter {
var index: Int
init(index: Int) {
self.index = index
}
}
class ViewModel: BindableObject {
let didChange = PassthroughSubject<ViewModel, Never>()
var counter = Counter(index: 0)
var timer: Timer!
init() {
timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true, block: { [weak self] timer in
guard let self = self else { return }
self.counter.index += 1
self.didChange.send(self)
})
}
}
#if DEBUG
struct ContentView_Previews : PreviewProvider {
static var previews: some View {
ContentView(viewModel: ViewModel())
}
}
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment