什么是新的“用于",“在...处",“在...中"? Swift3函数声明中的关键字? [英] What are the new "for", "at", "in" keywords in Swift3 function declarations?

查看:93
本文介绍了什么是新的“用于",“在...处",“在...中"? Swift3函数声明中的关键字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过Swift 2编写有关Swift的初学者教程.

I'm working through a beginners' tutorial on Swift that is written in Swift 2.

它包含类似(随机示例)的代码

It contains code like (random example)

override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {

在Swift 3(我正在使用XCode 8 Beta)中,这已经发生了变化,IDE很有帮助地将其转换为新的(漂亮!)表示法:

This has changed in Swift 3 (I'm using XCode 8 Beta), and the IDE helpfully converts this to the new (beautiful!) notation:

override func prepare(for segue: UIStoryboardSegue, sender: AnyObject?) {

让我感到困惑的是"for segue:"中的"for".我知道为什么它在那里,但是它在语法上是一种什么样的元素?参数是否命名为forfor seguesegue?

What confuses me here is the "for" in "for segue:". I get why it's there, but what kind of an element is it syntactically? Is the parameter named for, for segue, or segue?

这仅仅是装饰吗?除了帮助开发人员理解上下文之外,没有其他意义的元素吗?它还有其他作用吗?这个概念有名字吗?我可以用自己的方法使用它吗?

Is it mere decoration - an element with no meaning but to help the developer understand the context? Does it do anything else? Does the concept have a name? Can I use it in my own methods?

我看到"in"和"at"也发生了同样的情况.

I see the same happening with "in" and "at".

推荐答案

该语法允许您两次标记参数-一次在函数中使用(参数名称),一次在调用时使用(参数标签).默认情况下,这两个参数是相同的(例如您的示例中的sender),但是当使函数在调用站点上更具可读性时,它们是不同的:

The syntax allow you to label arguments twice - once for use within the function (the parameter name) and once for use when calling (the argument label). By default these two will be the same (like with sender in your example), but they differ when it makes a function more readable at the call site:

prepare(for: aSegue, sender: something)

句子的可读性比:

prepare(segue: aSegue, sender: something)

听起来您正在准备segue,而不是在准备 .

Which sounds like you're preparing the segue, not preparing for the segue.

for将是一个可怕的名称,在函数中内部使用它来引用segue,因此您可以根据需要使用其他名称.

for would be a dreadful name to use internally in the function to refer to the segue, so you can use a different one if you require.

该想法是为了满足有时相互矛盾的目标,即呼叫站点的可读性和实施中的合理命名.

The idea is to meet the sometimes conflicting goals of readability at the call site and sensible naming in the implementation.

在定义函数时,如果要使用单独的参数标签和参数名称,请先指定参数标签,然后再指定参数名称:

When defining a function, if you are going to use separate argument labels and parameter names, you specify the argument label first, and the parameter name second:

func sayHello(to name: String) {
    print("Hello " + name)
}

sayHello(to: "Pekka")

to仅在调用函数时具有相关性. name用于函数内部.

to only has relevance when calling the function. name is used inside the function.

这篇关于什么是新的“用于",“在...处",“在...中"? Swift3函数声明中的关键字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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