Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS Swift Decodable: Error: Cannot invoke initializer for type with no arguments

I'm getting error in initialising a struct, please see the screenshot attached below. After debugging I found that including review variable in the struct is giving problem. I can't figure out what I'm doing wrong. Can anyone help me out?

Tx

I'm copying code just in case you need to try it out

import UIKit

struct RootValue : Decodable {
    private enum CodingKeys : String, CodingKey {
        case success = "success"
        case content = "data"
        case errors = "errors"
    }
    let success: Bool
    let content : [ProfileValue]
    let errors: [String]
}

struct ProfileValue : Decodable {
    private enum CodingKeys : String, CodingKey {
        case id = "id"
        case name = "name"
        case review = "review" // including this gives error
    }

    var id: Int = 0
    var name: String = ""
    var review: ReviewValues // including this gives error
}

struct ReviewValues : Decodable{
    private enum CodingKeys : String, CodingKey {
        case place = "place"
    }

    var place: String = ""
}

class ViewController: UIViewController {

    var profileValue = ProfileValue()

    override func viewDidLoad() {
        super.viewDidLoad()
    }
}

enter image description here

like image 397
Matt Avatar asked Jun 20 '18 23:06

Matt


2 Answers

Review has no default value , You need to change this

var profileValue = ProfileValue()

to

var profileValue:ProfileValue?

OR

var review: ReviewValues?

OR

supply init method in ProfileValue struct

like image 153
Sh_Khan Avatar answered Nov 13 '22 10:11

Sh_Khan


Your ProfileValue struct doesn’t have a default value for the review property. That is why the compiler is unhappy, as you’re trying to create an instance of ProfileValue without providing default values for all of the non optional properties.

As a side note, all your coding key enum values just match the property names. You don’t need to include the coding keys enum if the names are the same.

like image 3
MultiColourPixel Avatar answered Nov 13 '22 10:11

MultiColourPixel