Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

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

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?

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

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")
over 4 years ago · Santiago Trujillo Report

0

Yet another solution is to use struct

struct Task: Codable {
    var name: String
}

let task = Task(name: "myname")
over 4 years ago · Santiago Trujillo Report

0

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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!