变异函数和属性

时间:2016-10-29 19:25:27

标签: swift

我有一个struct Town

人口为11

 struct Town {
    var population: Int = 11 {
        didSet(oldPopulation){
            print("The population has changed to \(population) from \(oldPopulation)")
        }
    }
}

我有一个变异功能

mutating func changePopulation(amount: Int) {
    population += amount     
}

我创建了一个僵尸类,它调用的函数可以将人口减少10个

final override func terrorizeTown() {
    guard var town = town else {
        return
    }
    town.population <= 0 ? print("no people to terrorize") : town.changePopulation(amount: -10)

    super.terrorizeTown()
}

当我运行main.swift文件时

var myTown = Town()
var fredTheZombie = Zombie()
fredTheZombie.name = "Fred"
fredTheZombie.town = myTown

//myTown.changePopulation(amount: 0)
print(myTown.population)

fredTheZombie.terrorizeTown()
print(myTown.population)

我不明白的是结果......

11
The population has changed to 1 from 11
Fred is terrorizing a town!
11

当我在属性上调用变异函数时,为什么当我再次打印(myTown.population)时,我会收到值11。我不明白..如果结果不是1,为什么我会得到11?

1 个答案:

答案 0 :(得分:1)

这是因为行guard var town = town生成了Town对象的副本。因此,它是变异的副本。