Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

392
Visualizações
'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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda