Reputation: 327
I'm trying to assign values to a Data Object from a static array in a file called FeaturedData, but I keep getting this annoying error: "Cannot assign to property: 'blurb' is a get-only property"
Here's my Model:
struct Featured: Codable {
var tagline: String
var title: String
var blurb: String
}
Here's my ViewModel:
import SwiftUI
class FeaturedViewModel: ObservableObject {
@Published var features = [FeaturedObjectViewModel]()
var data = FeaturedData()
func setFeatured() {
for featured in data.featureds {
let featureObject = FeaturedObjectViewModel(featured: featured)
featureObject.blurb = featured.blurb
self.features.append(featureObject)
}
}
}
struct FeaturedObjectViewModel {
let featured: Featured
var tagline: String {
self.featured.tagline
}
var title: String {
self.featured.title
}
var blurb: String {
self.featured.blurb
}
}
Here's the line that's prompting the error:
featureObject.blurb = featured.blurb
I don't get what wrong.
Upvotes: 0
Views: 74
Reputation: 18924
blurb Is a computed property. You can not assign the any values. It’s always returns.
Use init for FeaturedObjectViewModel
struct FeaturedObjectViewModel {
let featured: Featured
var tagline: String = “”
var title: String = “”
var blurb: String = “”
init(featured: Featured){
self.featured = featured
self.tagline = featured.tagline
self.title = featured.title
self.blurb = featured.blurb
}
}
Note : By doing this you don’t need to do this,
featureObject.blurb = featured.blurb
It will automatically assign to object value by init.
Also, in your code with computed property, no need to reassign value to featureObject var. When you get it, it will get featured.blurb value.
Upvotes: 1