加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

在Swift中使用函数参数名称

发布时间:2020-12-14 05:35:11 所属栏目:百科 来源:网络整理
导读:调用方法时,使用 Swift参数名称,除了第一个参数.为什么不使用名字? 使用Swift手册中的变体; var count2: Int = 0func incrementBy2(amount: Int,numberOfTimes times: Int) {count2 += amount * times} 这将工作; incrementBy2(2,numberOfTimes: 7) 然而,这
调用方法时,使用 Swift参数名称,除了第一个参数.为什么不使用名字?

使用Swift手册中的变体;

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

这将工作;

incrementBy2(2,numberOfTimes: 7)

然而,这给了我“无限参数标签”数量在调用“

incrementBy2(amount: 2,numberOfTimes: 7)

在这里有一个理由,还是它是“只是它的方式”的东西之一?

这是遵循Objective-C所使用的约定,其中第一个参数的名称与方法名称相结合.以下是一个例子:
- (void)incrementByAmount:(NSInteger)amount
            numberOfTimes:(NSInteger)times
{
    // stuff
}

您可以调用以下方法:

[self incrementByAmount:2 numberOfTimes:7];

通过将参数的名称并入到方法的名称中,阅读更加自然.在Swift中,您可以实现与以下相同的操作:

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

并调用方法如:

incrementByAmount(2,numberOfTimes: 7)

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

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

你可以这样调用方法:

incrementByAmount(incrementBy: 2,numberOfTimes: 7)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读