首页 > second name 是什么

second name 是什么

swift//import difference from functions and classes
class Counter {
    var count: Int = 0
    func incrementBy(amount: Int, numberOfTime times: Int) {
        count += amount * times
    }
}

var counter = Counter()
counter.incrementBy(2, numberOfTime: 7)

下面是原文的描述

Methods on classes have one important difference from functions. Parameter names in functions are used only within the function, but parameters names in methods are also used when you call the method (except for the first parameter). By default, a method has the same name for its parameters when you call it and within the method itself. You can specify a second name, which is used inside the method.

我不太理解numberOfTime times这里的作用 然后为什么可以这么表示
调用的时候却是 numberOfTime: 7 然后time确实获得了值


这段话主要说的是 function 和 类(Class)中 method 的区别。Function 中的参数名只是用在 function 内部使用,而 method 的参数名还可以在调用时候使用。在默认的情况下 method 的参数名和在它内部使用的参数(变量)是一致的,但是在 method 中你还可以为参数指定一个别名(second name)在 method 的内部使用。

第一个参数有点特殊,如果没有指定 second name 则在调用 method 的时候不能使用参数名来为指定的参数赋值,直接把参数值放在第一位即可。其他参数则没有这个要求,例如:

class Counter {
    var count: Int = 0
    func incrementBy(amount: Int, numberOfTime times: Int, test: Int) {
        count += amount * times * test
    }
}

var counter = Counter()
counter.incrementBy(1, numberOfTime: 4, test: 2)

在上面的例子中 numberOfTime 是参数名,而 times 则是在 method 内部使用的别名。

我想这样设计的好处是可以在调用的 method 的时候使用参数名来为指定的参数赋值,而无需按照参数顺序为参数赋值。


题主这是swift手册么?
网上有很多中文版http://www.ijavaee.com/swift/index.html

【热门文章】
【热门文章】