I have an ObservableObject class that can return 2 different @published vars (product or products), depending on the function I call.
But when I define the published vars, I am having an error message "Missing argument for parameter 'from' in call".
It just happens for the first published var. What's the mistake?
Thx
class ProductStore: ObservableObject {
@Published var product = ProductModel() //getting error here
@Published var products: [ProductModel] = []
func getProducts() {
ProductApi().getProducts() { (products) in
self.products.append(contentsOf: products)
}
}
func getProductById(productId: Int) {
ProductApi().getProductById(productId: productId) { (product) in
self.product = product
} }
}
Given that (as I understand from your previous posts) ProductModel is created from JSON, there's no need for an initalizer of the struct: the JSON decoding will do that. However, this means that "product" doesn't exist until created by your API call. The answer is to make product Optional: @Published var product : ProductModel?
This requires that any reference in your code to product (e.g. in subsequent processing) must test that product exists before using it e.g. if product == nil { return } or guard let product = product else { return }. If you are absolutely sure that product exists when you come to use it you can use product! (the exclamation mark means force unwrap), but if it doesn't exist the app will crash, as you've seen before I think.
Regards, Michaela