有人可以帮我解释这部分代码,无法得到它

时间:2016-10-26 05:55:11

标签: swift

为什么是最后一个命令:anotherGrowBy500()= 2500 我认为它假设= 2000。 任何帮助将不胜感激。

func makeGrowTracker(forGrowth growth: Int) ->() -> Int {
    var totalGrowth = 0
    func growthTracker()->Int {
        totalGrowth += growth
        return totalGrowth
    }
    return growthTracker
} 

var currentPopulation = 5422
let growBy500 = makeGrowTracker(forGrowth: 500)
growBy500()  //500
growBy500()  //1000
growBy500()  // 1500
currentPopulation += growBy500()
let anotherGrowBy500 = growBy500

anotherGrowBy500()

1 个答案:

答案 0 :(得分:0)

每当你拨打growBy500时,号码就会增加500。

让我们计算您拨打growBy500的次数:

var currentPopulation = 5422
let growBy500 = makeGrowTracker(forGrowth: 500)
growBy500()  //500               <-- 1
growBy500()  //1000              <-- 2
growBy500()  // 1500             <-- 3
currentPopulation += growBy500() <-- 4
let anotherGrowBy500 = growBy500 

anotherGrowBy500()               <-- 5

你把这个方法叫了五次! 500 * 5 = 2500!这就是你获得2500的原因。

令你困惑的部分可能是第五次或第四次通话。

在第四个调用中,虽然您要将内容分配给currentPopulatiion,但您仍在调用该方法!

每当你在方法后看到括号时,都会调用该方法!

要理解第五个电话,您需要了解它上面的一行:

let anotherGrowBy500 = growBy500 

您可以将此视为创建&#34;别名&#34; growBy500。您基本上是在说,每当我致电anotherGrowBy500时,我实际上都在呼叫growBy500