Home > database >  In Swift if I make something with 'let' than I can't change property but why keyPath
In Swift if I make something with 'let' than I can't change property but why keyPath

Time:02-28

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?

CodePudding user response:

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.

CodePudding user response:

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.

  • Related