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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With