iTranslated by AI
[Swift][Combine] Using @Published without ObservableObject
Sample Code
It is a common misunderstanding that @Published and ObservableObject must always be used together, but that is not the case.
When using ObservableObject
By adding ObservableObject, you can use it with variables annotated with @StateObject, @ObservedObject, or @EnvironmentObject.
import SwiftUI
// Add ObservableObject
class Hoge: ObservableObject {
@Published private(set) var mogmoge: Int = 0
}
// No compilation errors here 🌟
class Piyo {
@StateObject var hogeStateObject = Hoge()
@ObservedObject var hogeObservedObject = Hoge()
@EnvironmentObject var hogeEnvironmentObject: Hoge
}
Also, import SwiftUI is required to use @StateObject, @ObservedObject, and @EnvironmentObject.
In other words, ObservableObject is intended to be used in View implementations within SwiftUI.
(Please let me know if I am mistaken 🙇♂️)
When removing ObservableObject
If you remove ObservableObject, you can no longer use it with variables annotated with @StateObject, @ObservedObject, or @EnvironmentObject.
import SwiftUI
// Remove ObservableObject
class Hoge {
@Published private(set) var mogmoge: Int = 0
}
// Results in compilation errors 😭
class Piyo {
@StateObject var hogeStateObject = Hoge() // Generic struct 'StateObject' requires that 'Hoge' conform to 'ObservableObject'
@ObservedObject var hogeObservedObject = Hoge() // Generic struct 'ObservedObject' requires that 'Hoge' conform to 'ObservableObject'
@EnvironmentObject var hogeEnvironmentObject: Hoge // Generic struct 'EnvironmentObject' requires that 'Hoge' conform to 'ObservableObject'
}
You will get an error like: 'Generic struct 'StateObject' requires that 'Hoge' conform to 'ObservableObject'.'
Conclusion
- You can use
@Publishedeven in a class that does not conform toObservableObject. -
ObservableObjectis used when you want to utilize variables with@StateObject,@ObservedObject, or@EnvironmentObjectannotations = it is used for View implementations inSwiftUI.
That's all.
Sequel
In the following article, I introduce use cases for @Published outside of ObservableObject.
Discussion