简体   繁体   English

这个下划线在Swift中意味着什么?

[英]What does this underscore mean in Swift?

I used the map function in Swift to iterate on a bunch of subviews and remove them from a superview. 我使用Swift中的map函数迭代一堆子视图并从superview中删除它们。

self.buttons.map { $0.removeFromSuperview() }

When I upgraded from Swift 1.x to 2.0, Xcode gave a warning that the return value from map was unused. 当我从Swift 1.x升级到2.0时,Xcode发出警告,表示地图的返回值未使用。 So I assigned it with let x = ... and I got another warning: 所以我用let x = ...分配了它,我得到另一个警告:

在此输入图像描述

So I let Xcode fix the warning for me, and it gave me this: 所以我让Xcode为我修复警告,它给了我这个:

_ = self.buttons.map { $0.removeFromSuperview() }

What is the significance of an underscore when not in the context of a method parameter ? 不在方法参数的上下文中,下划线的意义是什么? What does it mean? 这是什么意思?

Edit: 编辑:

I do know that when a method parameter is anonymous, the underscore takes their place. 我知道当一个方法参数是匿名的时,下划线取代它们。 I'm talking about an underscore in the middle of a method. 我正在谈论方法中间的下划线。 It's not part of a message. 它不是信息的一部分。

An underscore denotes the fact that you need to set a variable, but you do not plan on using the variable in the future. 下划线表示您需要设置变量,但您不打算在将来使用该变量。 Instead of giving it an elaborate name, an underscore will be more simple and less clutter, especially in the case that the variable name doesn't matter. 下划线不是给它一个精心设计的名称,而是更简单,更简洁,特别是在变量名无关紧要的情况下。 (since you do not use it again.) (因为你不再使用它。)

A parameter whose local name is an underscore is ignored. 将忽略本地名称为下划线的参数。 The caller must supply an argument, but it has no name within the function body and cannot be referred to there. 调用者必须提供一个参数,但它在函数体中没有名称,并且不能在那里引用。 It is basically a parameter placeholder that you are not going to use for anything in the body. 它基本上是一个参数占位符,您不会将其用于正文中的任何内容。

If I'm not mistaken this carried over from Objective-C. 如果我没有弄错,这是从Objective-C延续下来的。 When you did not "use" your pointer at all in the app, you would get a warning. 如果您没有在应用程序中“使用”指针,则会收到警告。 In Swift 2 I believe they tried to implement something similar. 在Swift 2中,我相信他们试图实现类似的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM