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

234
Visualizações
In Swift if I make something with 'let' than I can't change property but why keyPath is different?
class Person{
    var name: String
    init(_ name: String){
        self.name = name
    }
}

struct Stuff{
    var name: String
    var owner: Person1
}

let jenna = Person("jenna")

var mac = Stuff(name: "Macbook pro", owner: jenna)

let ownerKeyPath = \Stuff.owner.name

mac[keyPath: ownerKeyPath] = "jerry"     

I made jenna with 'let' keyword but if I use keyPath than I could change jenna's property. How does it works?

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

KeyPaths are irrelevant.

You made Person.name variable. As such, mac.owner.name = "jerry" works fine.

But it won't if you change name to let. That will make ownerKeyPath a KeyPath, not the ReferenceWritableKeyPath subclass of KeyPath that it is in your code. As with let constants, you can't set values using the KeyPath class.

over 4 years ago · Santiago Trujillo Relatório

0

Person is a reference type (a class). For a reference type, let just means that the reference itself cannot change, so jenna cannot be made to point to another object. But you can change any var properties within it (such as name. KeyPaths aren't related here. The same is true of regular property access:

mac.owner.name = "jerry"

If you want Person to behave like a value, so that its properties cannot change when it is marked with let (but can when it is marked with var), then it needs to be a struct, not a class. Then it will behave like Stuff.

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