简体   繁体   中英

Changing the value of a constant in a class

Working through Apple's Swift Programming Guide I came across this example in the explanation of ARC;

class Person {
    let name: String
    init(name: String) {
        self.name = name
        println("\(name) is being initialized")
    }
    deinit {
        println("\(name) is being deinitialized")
    }
}

var reference1: Person?
var reference2: Person?
var reference3: Person?

I understand the idea that because the variables are of the option type they are initialized with a value of nil and do not reference a Person instance. So the following makes sense to me;

reference1 = Person(name: "John Appleseed")

However I was experimenting and was surprised to see I could also do this;

reference1 = Person(name: "Johnny Appleseed")

I was expecting the code to error since I was trying to change the constant "name" property. Not only can I change this property I also got the message "Johnny Appleseed is being initialized". How can I be initializing a constant twice?

You're not actually changing the name property of your existing Person instance.

What you're doing is creating a new Person , and giving him the name "Johnny". Your old Person with the name "John" will be deallocated automatically:

reference1 = Person(name: "John Appleseed")
reference1 = Person(name: "Johnny Appleseed") // "John" is now gone.

Unless you have some other variable pointing to "John", that instance will be deallocated.

This would cause a compilation error:

reference1 = Person(name: "John Appleseed")
reference1.name = "Johnny Appleseed"

Because you'd be trying to change the value of a property defined using let .

By calling Person(name: "Johnny Appleseed") you creating a new Person object that replaces the old Person object referenced by reference1 . The constant property name of the old Person object is not changed at all, thus no error is issued.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM