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?
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")
Yet another solution is to use struct
struct Task: Codable {
var name: String
}
let task = Task(name: "myname")
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.