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

查看:31
本文介绍了什么是新的“for"、“at"、“in"?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 segue 还是segue?

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)

这听起来像是你在准备转场,而不是准备转场.

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.

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

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