I have a Codable class:
class Task: Codable {
var name: String
}
When I try to instantiate it:
let newTask = Task()
allTasks.append(newTask)
It gives me error:
Missing argument for parameter 'from' in call
All I want is to insert a new object (newTask) into an array. What is the simplest way to do this?
To make a Swift object codable, you have to make the data type conform to the Codable protocol. If you only want to decode your objects, you can use the Decodable protocol. Similar if you only want to encode objects, use the Encodable protocol.
The simplest way to make a type codable is to declare its properties using types that are already Codable . These types include standard library types like String , Int , and Double ; and Foundation types like Date , Data , and URL .
The Codable protocol in Swift is really a union of two protocols: Encodable and Decodable . These two protocols are used to indicate whether a certain struct, enum, or class, can be encoded into JSON data, or materialized from JSON data.
Yet another solution is to use struct
struct Task: Codable {
var name: String
}
let task = Task(name: "myname")
You can inherit the initializer from NSObject:
class Task: NSObject, Codable {
var name: String = ""
}
let newTask = Task()
If you don't want to inherit NSObject, then just create your own initializer:
class Task: Codable {
var name: String?
init() {
}
}
If you don't want to make name
optional (or set it to a default), it has to be initialized in init() such as:
class Task: Codable {
var name: String
init(withName name: String) {
self.name = name
}
}
let newTask = Task(withName: "ikevin8me")
Your Task
class doesn't provide its own initializer so it gets the one defined in the Codable
protocol (which it gets from the Decodable
protocol).
Either add your own explicit init
that takes a name
parameter or change your class to a struct. Either way, you need to create a Task
by passing in a name value so the name
property can be initialized.
None of this addresses the fact that the code you posted makes no use of Codable
so maybe there is no need for your class (or struct) to conform to Codable
.
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