I am trying to create a new instance of a codable struct
@State private var parcel = Parcel()
but I'm getting this error:
Missing argument for parameter 'from' in call Insert 'from: <#Decoder#>'
struct Parcel: Codable {
var created_at: String
var height: Double
var id: String
var length: Double
var mode: String?
var object: String
var predefined_package: String?
var updated_at: String?
var weight: Double
var width: Double
}
Every object in Swift needs an initializer: some code to set up the object when it is first created. If your object is an instance of a class, the initializer needs to be explicitly defined by you. However if the object is an instance of a struct, Swift implicitly defines an initializer. For example, this struct
struct Foo {
let bar: Int
}
implicitly gets an initializer that looks like this
init(bar: Int) {
self.bar = bar
}
Initializers can also be implicitly created through protocol extensions. That means if your struct inherits a protocol (such as Codable
), the protocol can define additional initializers for you. For this simple example, Codable
would add something like this
init(from decoder: Decoder) throws {
// decode a key value pair with name "bar" and an Int value using decoder
let decodedBar = try ...
self.init(bar: decodedBar)
}
In your case, when you write parcel = Parcel()
you are calling this kind of initializer
init() {
// initialize somehow with no input!
}
But you never defined anything like that! The compiler is suggesting that you call the initalizer you got from Codable
since it's a close match, but that's probably not what you want either.
You can either define that missing initializer, or define default values for all of your struct's members. If you do that, the implicit initializer defined by Swift will have no arguments, making your code valid. For example
struct Foo {
let bar: Int = 3
}
let f = Foo() // now this is valid, implicit init has no arguments
If you wrote your "struct" inside Package Dependencies and want to create an object outside, make the init public.
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