在 Swift 中使用函数参数名称 [英] Using Function Parameter Names in Swift

查看:29
本文介绍了在 Swift 中使用函数参数名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Swift 中,调用方法时会使用参数名称,但第一个参数除外.为什么不使用名字?

In Swift parameter names are used when you call a method, except for the first parameter. Why is the first name not used?

使用 Swift 手册中的一个变体;

Using a variation from the Swift manual;

var count2: Int = 0
func incrementBy2(amount: Int, numberOfTimes times: Int) {
count2 += amount * times}

这行得通;

incrementBy2(2, numberOfTimes: 7)

但是这给了我调用中的无关参数标签'amount'"

However this gives me "Extraneous argument label 'amount' in call"

incrementBy2(amount: 2, numberOfTimes: 7)

这有什么原因吗,还是就是这样"的事情之一?

Id there a reason for this or is it one of those "just the way it is" things?

推荐答案

这是遵循我们在 Objective-C 中都习惯的约定,其中第一个参数的名称与方法名称组合在一起.举个例子:

This is to follow an convention we were all used to from Objective-C, where the name of the first parameter is combined with the method name. Here's an example:

- (void)incrementByAmount:(NSInteger)amount
            numberOfTimes:(NSInteger)times
{
    // stuff
}

你可以这样调用方法:

[self incrementByAmount:2 numberOfTimes:7];

通过将参数名称合并到方法名称中,阅读起来感觉更自然.在 Swift 中,您可以通过以下方式实现相同的效果:

And it feels more natural to read by incorporating the name of the parameter into the method's name. In Swift, you can achieve the same with the following:

func incrementByAmount(amount: Int, numberOfTimes: Int) {
    // same stuff in Swift
}

并调用如下方法:

incrementByAmount(2, numberOfTimes: 7)

如果您不想使用这个约定,Swift 可以让您更明确地定义单独的内部和外部参数名称,如下所示:

If you don't want to use this convention, Swift gives you the ability to be more explicit and define separate internal and external parameter names, like so:

func incrementByAmount(incrementBy amount: Int, numberOfTimes: Int) {
    // same stuff in Swift
    // access `amount` at this scope.
}

你可以这样调用方法:

incrementByAmount(incrementBy: 2, numberOfTimes: 7)

这篇关于在 Swift 中使用函数参数名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆