函数实际参数标签和形式参数名
每一个函数的形式参数都包含实际参数标签和形式参数名。实际参数标签用在调用函数的时候;在调用函数的时候每一个实际参数前边都要写实际参数标签。形式参数名用在函数的实现当中。默认情况下,形式参数使用它们的形式参数名作为实际参数标签。
1 2 3 4 5 | func someFunction(firstParameterName: Int, secondParameterName: Int) { // In the function body, firstParameterName and secondParameterName // refer to the argument values for the first and second parameters. } someFunction(firstParameterName: 1, secondParameterName: 2) |
左右的形式参数必须有唯一的名字。尽管有可能多个形式参数拥有相同的实际参数标签,唯一的实际参数标签有助于让你的代码更加易读。
指定实际参数标签
在提供形式参数名之前写实际参数标签,用空格分隔:
1 2 3 4 | func someFunction(argumentLabel parameterName: Int) { // In the function body, parameterName refers to the argument value // for that parameter. } |
注意
如果你为一个形式参数提供了实际参数标签,那么这个实际参数就必须在调用函数的时候使用标签。
这里有另一个函数 greet(person:)的版本,接收一个人名字和家乡然后返回对这个的问候:
1 2 3 4 5 | func greet(person: String, from hometown: String) -> String { return "Hello \(person)! Glad you could visit from \(hometown)." } print(greet(person: "Bill", from: "Cupertino")) // Prints "Hello Bill! Glad you could visit from Cupertino." |