Created
June 6, 2019 23:08
-
-
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.
This file contains hidden or 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 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