Home > Enterprise >  Insert 'from: <#Decoder#>'
Insert 'from: <#Decoder#>'

Time:10-08

I have the following Model:

struct MyModel: Codable, Hashable {
    let data: ASubModelData
    let error: Bool?
    let error_message: String?
    let error_code: Int?
}

and I'm trying to create a variable in a view so I can then assign the values to it like this:

@State var myVar: MyModel? = MyModel()

but it's throwing an error:

Insert 'from: <#Decoder#>'

enter image description here

If I hit fix, it would be like:

@State var myVar: MyModel? = MyModel(from: Decoder)

and that's wrong, it also gives an error, how can I create a variable that is an empty instance of that model?

CodePudding user response:

Your struct has no initializer other than the one for decoding. You have to add the initializer init():

init() {
  data = ?
  error = nil
  error_message = nil
  error_code = nil
}

However, since MyModel contains properties that are not optional, it would be probably better to initialize it with a nil:

@State var myVar: MyModel?
  • Related