Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift Init does not conform to expected type 'Decoder'

At the moment, I have a struct that conforms to Codable:

public struct Preference: Codable {

    public let id: String

}

When I try to initialize the object using the following:

let preference = Preference(id: "cool")

I get the following error:

Argument type 'String' does not conform to expected type 'Decoder'

How can I fix this issue and initialize the struct properly?

like image 256
Adam Cooper Avatar asked Jan 09 '18 19:01

Adam Cooper


1 Answers

When struct is created without explicit initializer

public struct Preference {
    public let id: String
}

it gets internal init(id: String) initializer for free. Internal means that using it from another target will result in compiler error.

Adding Decodable to your struct also adds public init(from: Decoder) initializer to this struct.

So initial struct is equivalent to the following

public struct Preference: Codable {
    public let id: String

    internal init(id: String) {
        self.id = id
    }

    public init(from: Decoder) {
        // generated decoding code
    }
}

When you try to create an instance using Preference(id: "cool") from another target there is only one public initializer: the one with the decoder. Compiler tries to use it by casting String to Decoder and it fails.

To resolve the original issue you need to add public init(id: String) initializer explicitly.

like image 81
Maxim Kosov Avatar answered Oct 06 '22 20:10

Maxim Kosov