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

393
Vistas
'let' property may not be initialized directly; use "self.init(...)" or "self = ..." instead

I want to try to write a default init in a protocol extension, so I did this:

protocol P {
    var data: [AnyHashable: Any] { get }
    init(_ s: String)
}

extension P {
    init(_ s: String) {
        self.data = ["s": s]
    }
}

But I'm getting this error:

'let' property 'data' may not be initialized directly; use "self.init(...)" or "self = ..." instead

I have no idea what it means. Thanks for your help!

over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

The error says that the variable cannot be initialized in the protocol extension because it's declared as constant { get }

But even if you declare the variable { get set } you can't use the init method anyway without a constraint to a concrete type or an associated type.

over 4 years ago · Santiago Trujillo Denunciar

0

import PlaygroundSupport

protocol P {
    var data: [AnyHashable: Any] { get }
    var _data: [AnyHashable: Any] { get set }
    static func generator(_ s: String) -> P
    init()
}

extension P {
    static func generator(_ s: String) -> P {
        var p = self.init()
        p._data = ["s": s]
        return p
    }
}

class A: P {
    required init() { }
    var data: [AnyHashable : Any] {
        return _data
    }
    var _data: [AnyHashable : Any] = [:]
}

let a = A.generator("some")
print(a.data)

PlaygroundPage.current.finishExecution()

I think this is the closest code you want. The problem is that _data is shared by other classes.

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