Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the simplest way to instantiate a new Codable object in Swift?

Tags:

swift

codable

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?

like image 729
ikevin8me Avatar asked Jan 22 '19 05:01

ikevin8me


People also ask

How do you make a Codable model in Swift?

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.

How do you implement Codable?

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 .

What is the Codable protocol in Swift?

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.


Video Answer


3 Answers

Yet another solution is to use struct

struct Task: Codable {
    var name: String
}

let task = Task(name: "myname")
like image 185
taka Avatar answered Oct 20 '22 10:10

taka


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")
like image 42
Jeshua Lacock Avatar answered Oct 20 '22 10:10

Jeshua Lacock


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.

like image 2
rmaddy Avatar answered Oct 20 '22 10:10

rmaddy