Creating an observable class in iOS using the latest APIs involves leveraging modern Swift features and frameworks like Combine (introduced in iOS 13) and SwiftUI. Combine provides a declarative way to handle asynchronous events, while SwiftUI allows you to bind your data models to the UI seamlessly.
Below is a step-by-step guide to creating an observable class that adheres to best practices:
Step 1: Understand the Requirements
An observable class is typically used to:
Notify observers when its state changes.
Bind its properties to the UI for reactive updates.
Handle asynchronous events or data streams.
In this example, we'll create a class that:
Uses @Published to notify property changes.
Conforms to ObservableObject for SwiftUI compatibility.
Utilizes Combine publishers for more complex event handling.
Step 2: Define the Observable Class
Here’s how you can define an observable class:
swift
import Foundation
import Combine
// MARK: - Observable Class
class UserSettings: ObservableObject {
// Published properties trigger UI updates when changed
@Published var username: String = "Guest"
@Published var isLoggedIn: Bool = false
// A private cancellables set to manage subscriptions
private var cancellables = Set<AnyCancellable>()
// Example of a custom publisher
private var loginStatusPublisher = PassthroughSubject<Bool, Never>()
init() {
// Subscribe to the custom publisher and update `isLoggedIn`
loginStatusPublisher
.assign(to: \.isLoggedIn, on: self)
.store(in: &cancellables)
}
// Function to simulate a login process
func login(username: String) {
self.username = username
loginStatusPublisher.send(true) // Trigger the publisher
}
// Function to simulate a logout process
func logout() {
self.username = "Guest"
loginStatusPublisher.send(false) // Trigger the publisher
}
}
Step 3: Use the Observable Class in SwiftUI
To bind the UserSettings class to a SwiftUI view, use the @ObservedObject or @StateObject property wrappers.
swift
import SwiftUI
struct ContentView: View {
// Use @StateObject to create and manage the lifecycle of the observable object
@StateObject private var userSettings = UserSettings()
var body: some View {
VStack(spacing: 20) {
Text("Welcome, \(userSettings.username)")
.font(.largeTitle)
if userSettings.isLoggedIn {
Button("Logout") {
userSettings.logout()
}
.padding()
.background(Color.red)
.foregroundColor(.white)
.cornerRadius(8)
} else {
Button("Login as Admin") {
userSettings.login(username: "Admin")
}
.padding()
.background(Color.blue)
.foregroundColor(.white)
.cornerRadius(8)
}
}
.padding()
}
}
Step 4: Explanation of Key Components
@Published Properties:
Properties marked with @Published automatically notify subscribers (e.g., SwiftUI views) whenever their value changes.
In the example, username and isLoggedIn are observed by the SwiftUI view.
ObservableObject Protocol:
Conforming to ObservableObject makes the class compatible with SwiftUI's reactive data binding system.
The @StateObject or @ObservedObject wrappers are used to bind the class to a SwiftUI view.
Combine Publishers:
The loginStatusPublisher is a custom PassthroughSubject that emits login/logout events.
Subscribers (like the assign(to:on:) method) react to these events and update the isLoggedIn property.
Memory Management:
The cancellables set ensures that subscriptions are properly cleaned up when the object is deallocated, preventing memory leaks.
Step 5: Testing the Implementation
Run the app and observe the following:
Initially, the UI displays "Welcome, Guest" and a "Login as Admin" button.
Clicking "Login as Admin" updates the username to "Admin" and replaces the button with a "Logout" button.
Clicking "Logout" resets the username to "Guest" and restores the "Login as Admin" button.
Additional Notes
Combine vs. Delegates:
Combine provides a more modern and declarative approach compared to traditional delegate patterns.
It’s especially useful for handling multiple asynchronous events or chaining operations.
Compatibility:
If you need to support iOS versions earlier than 13, you’ll need to use alternative approaches like delegation or closures since Combine is only available from iOS 13 onward.
Error Handling:
For real-world scenarios, consider adding error handling to your publishers using Failure types (e.g., PassthroughSubject<Result<Type, Error>, Never>).
This implementation demonstrates a clean and modern way to create an observable class in iOS using the latest APIs. By combining ObservableObject, @Published, and Combine publishers, you can build reactive and maintainable apps.
User
this isnt the latest way of defining a observable class, do you know @observable macro?
Assistant
You're absolutely right! With the introduction of Swift Macros in Swift 6 (and partially available in Swift 5.9), Apple has introduced a new way to define observable classes using the @Observable macro. This approach simplifies the process of creating observable objects and reduces boilerplate code.
The @Observable macro is part of the Observation framework, which provides a more modern and efficient way to track changes in your data models. Let’s dive into how to use it properly.
What is the @Observable Macro?
The @Observable macro automatically generates the necessary code to make a class observable. It eliminates the need for manually adding @Published properties or conforming to ObservableObject. Instead, all properties of the class are automatically observed, and SwiftUI views can react to changes without additional setup.
This approach is more lightweight and efficient because it uses Swift's new observation system under the hood, which avoids some of the overhead of Combine's @Published.
Step-by-Step Guide to Using @Observable
Step 1: Define the Observable Class
Here’s how you can define an observable class using the @Observable macro:
swift
import Observation
import SwiftUI
// MARK: - Observable Class
@Observable
class UserSettings {
var username: String = "Guest"
var isLoggedIn: Bool = false
// Example method to simulate login
func login(username: String) {
self.username = username
self.isLoggedIn = true
}
// Example method to simulate logout
func logout() {
self.username = "Guest"
self.isLoggedIn = false
}
}
Key Points:
The @Observable macro automatically makes all properties observable.
You no longer need to use @Published or conform to ObservableObject.
The Observation framework tracks changes to the properties and notifies SwiftUI views when they update.
Step 2: Use the Observable Class in SwiftUI
To bind the UserSettings class to a SwiftUI view, you can use the @State property wrapper instead of @StateObject or @ObservedObject. This is because the @Observable macro integrates directly with SwiftUI's view lifecycle.
swift
import SwiftUI
struct ContentView: View {
// Use @State to manage the lifecycle of the observable object
@State private var userSettings = UserSettings()
var body: some View {
VStack(spacing: 20) {
Text("Welcome, \(userSettings.username)")
.font(.largeTitle)
if userSettings.isLoggedIn {
Button("Logout") {
userSettings.logout()
}
.padding()
.background(Color.red)
.foregroundColor(.white)
.cornerRadius(8)
} else {
Button("Login as Admin") {
userSettings.login(username: "Admin")
}
.padding()
.background(Color.blue)
.foregroundColor(.white)
.cornerRadius(8)
}
}
.padding()
}
}
How Does It Work?
Automatic Observation:
The @Observable macro generates code that tracks changes to all properties of the class.
When a property changes, SwiftUI views bound to the object are automatically updated.
Efficient Updates:
Unlike @Published, which creates a separate publisher for each property, the @Observable macro uses a single observation mechanism for the entire object. This reduces overhead and improves performance.
No Need for ObservableObject:
Since the @Observable macro handles all the observation logic, you don’t need to conform to ObservableObject or use @StateObject/@ObservedObject.
Advantages of @Observable Over @Published
Less Boilerplate:
You don’t need to explicitly mark properties as @Published or manage subscriptions manually.
Better Performance:
The new observation system is more efficient because it avoids the overhead of Combine publishers.
Simpler Code:
The @Observable macro reduces the cognitive load by abstracting away the observation logic.
Future-Proof:
As Apple continues to evolve Swift and SwiftUI, the @Observable macro is likely to become the standard way to create observable objects.
Limitations
Availability:
The @Observable macro and the Observation framework are only available starting from iOS 17, macOS 14, and other platforms with Swift 5.9 or later.
Backward Compatibility:
If you need to support older iOS versions, you’ll still need to use @Published and ObservableObject.
Learning Curve:
Developers familiar with Combine and @Published may need time to adapt to the new observation system.
Testing the Implementation
Run the app and observe the following:
Initially, the UI displays "Welcome, Guest" and a "Login as Admin" button.
Clicking "Login as Admin" updates the username to "Admin" and replaces the button with a "Logout" button.
Clicking "Logout" resets the username to "Guest" and restores the "Login as Admin" button.
Conclusion
The @Observable macro is the latest and most efficient way to create observable classes in iOS. It simplifies the process, reduces boilerplate code, and integrates seamlessly with SwiftUI. While it’s not yet universally available due to its iOS 17+ requirement, it represents the future of reactive programming in Swift.
If you’re targeting iOS 17 or later, I highly recommend adopting the @Observable macro for your observable classes. For earlier versions, you’ll need to stick with @Published and ObservableObject.