iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🌾

[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 @Published even in a class that does not conform to ObservableObject.
  • ObservableObject is used when you want to utilize variables with @StateObject, @ObservedObject, or @EnvironmentObject annotations = it is used for View implementations in SwiftUI.

That's all.

Sequel

In the following article, I introduce use cases for @Published outside of ObservableObject.

GitHubで編集を提案

Discussion