功能参数名称不符合文档 [英] Function Parameter Names don't behave according to documentation

查看:79
本文介绍了功能参数名称不符合文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据手册:

函数参数名称

这些参数名称仅在正文中使用函数本身,并且在调用函数时不能使用。这些参数名称称为本地参数名称,因为它们只能在函数体内使用。

These parameter names are only used within the body of the function itself, and cannot be used when calling the function. These kinds of parameter names are known as local parameter names, because they are only available for use within the function’s body.

    join("hello", "world", ", ")


func join(s1: String, s2: String, joiner: String) -> String {
    return s1 + joiner + s2
}

但是代码没有编译:

错误:缺少参数标签's2:joiner:'in call
join(hello,world,,)
^
s2:joiner:

error: missing argument labels 's2:joiner:' in call join("hello", "world", ", ") ^ s2: joiner:

只有当我尝试使用一个参数时,它才会成为可选项

Only when I try with one parameter, it becomes optional

    join("hello")


func join(s1: String) -> String {
    return s1
}

更令人讨厌,甚至不允许完全使用第一个:

Even more annoying, it's not even permissible to use the first one at all:

    join(s1: "hello")

无关的参数标签's1:'在电话中
加入(s1:你好)

extraneous argument label 's1:' in call join(s1: "hello")

在阅读涵盖函数的文档时,我是否遗漏了任何内容?

Did I miss anything while reading the documentation covering functions?

推荐答案

函数和方法之间的行为有所不同。

The behavior is different between functions and methods.

对于方法,默认行为是使用本地名称作为第一个之后所有参数的外部名称。

For a method, the default behavior is to use the local name as the external name for all arguments after the first.

您可以将方法默认为:

func method(_ arg1: AnyObject?, #arg2: AnyObject?, #arg3: AnyObject?) {
}

您始终可以明确说明您的需求处理参数

You can always explicitly state how you want to handle arguments

func join(_ s1: String, _ s2: String, _ joiner: String) -> String {
    return s1 + joiner + s2
}



Swift编程语言|语言指南|方法



The Swift Programming Language | Language Guide | Methods


具体来说,Swift默认情况下在方法中给出一个本地参数名称的第一个参数名称,并给出第二个和后续参数默认命名本地和外部参数名称。此约定与您在编写Objective-C方法时熟悉的典型命名和调用约定相匹配,并且无需限定参数名称即可进行表达式方法调用。

Specifically, Swift gives the first parameter name in a method a local parameter name by default, and gives the second and subsequent parameter names both local and external parameter names by default. This convention matches the typical naming and calling convention you will be familiar with from writing Objective-C methods, and makes for expressive method calls without the need to qualify your parameter names.

这篇关于功能参数名称不符合文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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