I am trying to create a new instance of a codable class, but I am not sure how to:
var x = Articles();
gives me the following error:
Missing argument for parameter 'from' in call
class Articles: Codable {
let value: [Article]?
}
I don't understand since this is a parameterless class. I have no idea what the from parameter is all about.
I don't understand since this is a parameterless class. I have no idea what the from parameter is all about.
I get no error when I run the following:
class Articles: Codable {
let value: [Articles]?
init() {
value = nil
print("in init()")
}
}
var x = Articles()
output:
in init()
And without init()
:
class Articles: Codable {
let value: [Articles]?
// init() {
// value = nil
// print("in init()")
// }
}
var x = Articles() //Missing argument for parameter 'from' in call
First, read this:
Automatic Initializer Inheritance
As mentioned above, subclasses do not inherit their superclass initializers by default. However, superclass initializers are automatically inherited if certain conditions are met. In practice, this means that you do not need to write initializer overrides in many common scenarios, and can inherit your superclass initializers with minimal effort whenever it is safe to do so.
Assuming that you provide default values for any new properties you introduce in a subclass, the following two rules apply:
Rule 1 If your subclass doesn’t define any designated initializers, it automatically inherits all of its superclass designated initializers.
If you look at the docs, Codable
is a typealias
for the Decodable
protocol (a protocol is like an interface in java). Protocols specify functions that a class must implement if they adopt the protocol. Your Articles
class adopts the Decodable
protocol. However, the docs for Decodable say,
init(from: Decoder)
Creates a new instance by decoding from the given decoder. Required. Default implementation provided.
Protocols can actually implement functions by using extensions, which are then inherited by the class adopting the protocol.
As a result, the only designated initializer for your class is the one defined in the Decodable
protocol, which takes one argument--which you inherit according to Rule 1
. On the other hand, when you explicitly define another designated initializer in your class that takes no arguments, then you will call that initializer when you provide no arguments.
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