I've added an Observable Object to my class DetailViewModel, but I am getting an error "Class 'DetailViewModel' has no initializers". Can anyone explain why?
import Foundation
import UIKit
@MainActor
class DetailViewModel: ObservableObject{
@Published var strMeal: String = ""
@Published var strInstructions: String
@Published var strIngredient: String
@Published var strMeasure: String
@Published var strMealThumb:URL?
private func loadMealDetails(idMeal: String) async {
do {
let mealDetailResponse = try await WebServiceRequest().loadData(url: Constants.Urls.getMealByIdUrl(strMeal)) { data in
return try? JSONDecoder().decode(MealDetailModel.self, from:data )
}
} catch {
print(error)
}
}
CodePudding user response:
You have defined some properties (strInstructions
, strIngredient
, and strMeasure
) that don't have initial values specified. Unlike struct
s, which get synthesized initializers (eg the compiler makes a initializer for us), with a class
, we have to create an initializer ourselves (or give all of the properties default values).
With default values, it may look like:
@MainActor
class DetailViewModel: ObservableObject{
@Published var strMeal: String = ""
@Published var strInstructions: String = ""
@Published var strIngredient: String = ""
@Published var strMeasure: String = ""
@Published var strMealThumb:URL?
}
Or, with an initializer, it could be something like:
@MainActor
class DetailViewModel: ObservableObject{
@Published var strMeal: String = ""
@Published var strInstructions: String
@Published var strIngredient: String
@Published var strMeasure: String
@Published var strMealThumb:URL?
init(strInstructions: String, strIngredient: String, strMeasure: String) {
self.strInstructions = strInstructions
self.strIngredient = strIngredient
self.strMeasure = strMeasure
}
}
You may also want to accept values for strMeal
and strMealThumb
in your initializer -- it's up to you.