Search code examples
iosswiftnetwork-programmingcodableencodable

Argument type does not conform to Encodable


I am trying to create a Struct for a POST request. The struct conforms, to the best of my knowledge to the Codable typealias but I keep getting the error

Argument type 'RegisterUserRequest.Type' does not conform to expected type 'Encodable' " when passing it in as a parameter to my JSONEncoder.

I have tried to conform only to Encodable, to write the suggested required init() but nothing seems to work.

This is the way my Struct looks like


struct RegisterUserRequest: Codable {
    var firstName: String
    var lastName: String
    var email: String
    var phoneNumber: String
    var dateOfBirth: String

    enum CodingKeys: String, CodingKey {
        case firstName = "first_name"
        case lastName = "last_name"
        case email
        case phoneNumber = "phone"
        case dateOfBirth = "date_of_birth"
    }
}

This is the error I get

enter image description here


Solution

  • Here you need to pass an object of a type that conforms to Codable / Encodable not the type itself

    do {
        let instance = RegisterUserRequest(firstname:////////......
        let data = try JSONEncoder().encode(instance)
    }
    catch {
      print(error)
    }