Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

165
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda