import SwiftUI
class PremiumFeaturesViewModel: ObservableObject {
@Published var features: [String] = []
@Published var isLoading = false
func loadFeatures() async {
await MainActor.run {
self.isLoading = true
}
try? await Task.sleep(nanoseconds: 2_000_000_000) // simulate 2 seconds delay
let loadedFeatures = ["Feature 1", "Feature 2", "Feature 3"]
await MainActor.run {
self.features = loadedFeatures
self.isLoading = false
}
}
}
struct PremiumFeaturesView: View {
@StateObject private var viewModel = PremiumFeaturesViewModel()
var body: some View {
VStack {
Text("Premium Features Demo")
.font(.title)
.padding()
if viewModel.isLoading {
Text("Loading data...")
.padding()
} else {
List(viewModel.features, id: \.self) { feature in
Text(feature)
}
}
Button("Refresh") {
Task {
await viewModel.loadFeatures()
}
}
.padding()
}
.task {
await viewModel.loadFeatures()
}
}
}
struct PremiumFeaturesView_Previews: PreviewProvider {
static var previews: some View {
PremiumFeaturesView()
}
}This solution uses the MVVM pattern by creating a PremiumFeaturesViewModel class that manages the data and loading state. The view observes this model using @StateObject to update the UI reactively.
Data loading is simulated asynchronously with a 2-second delay using Swift concurrency (async/await). While loading, the UI shows a "Loading data..." message. After loading, it displays a list of premium features.
The Refresh button triggers data reload by calling the async load function again.
This separation of concerns and use of modern Swift patterns makes the app code clean, reusable, and responsive, which are key qualities of premium apps.