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

Matt picture Matt · Jun 21, 2018 · Viewed 13.7k times · Source

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

Answer

Sh_Khan picture Sh_Khan · Jun 21, 2018

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