I have a minimal reproducible example in SwiftUI that demonstrates an issue with view updates when using a class vs a struct. The view updates correctly when using a struct, but it doesn’t update when using a class. Below is the code:
SimpleView.swift
import SwiftUI
import Foundation
struct SimpleView: View {
@StateObject private var viewModel = SampleViewModel()
var body: some View {
VStack {
Text(viewModel.timeCounter.showerTimeMinutes)
Button("Update Minutes Class") {
viewModel.timeCounter.showerTimeMinutes = "15"
}
VStack {
Text(viewModel.timeCounterStruct.showerTimeMinutes)
Button("Update Minutes Struct") {
viewModel.timeCounterStruct.showerTimeMinutes = "15"
}
}
VStack {
Text(viewModel.timerCounterPublisher.showerTimeMinutes)
Button("Update Minutes Class with Publisher") {
viewModel.timerCounterPublisher.showerTimeMinutes = "15"
}
}
}
}
}
struct SimpleView_Previews: PreviewProvider {
static var previews: some View {
SimpleView()
}
}
SampleViewModel.swift
class SampleViewModel: ObservableObject {
@Published var timeCounter = SampleTimeCounter()
@Published var timeCounterStruct = SampleTimeCounterStruct()
@Published var timerCounterPublisher = SampleTimeCounterPublihser()
}
// This is support class that will save the shower time for next time.
class SampleTimeCounter {
var showerTimeMinutes = "00"
}
class SampleTimeCounterPublihser: ObservableObject {
@Published var showerTimeMinutes = "00"
}
struct SampleTimeCounterStruct {
var showerTimeMinutes = "00"
}
When I update the showerTimeMinutes property in SampleTimeCounterStruct (which is a struct), the view updates as expected. However, when I update the showerTimeMinutes property in SampleTimeCounter (which is a class), the view does not update. However I have used the @Publshed property and it not updating the view as well.