本文介绍了为什么我需要快速下划线?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里它说,注意:_ 意味着我不在乎那个值"",但是来自 JavaScript,我不明白这是什么意思.

Here it says, "Note: the _ means "I don’t care about that value"", but coming from JavaScript, I don't understand what that means.

我可以打印这些函数的唯一方法是在参数前使用下划线:

The only way I can get these functions to print was by using the underscores before the parameters:

func divmod(_ a: Int, _ b:Int) -> (Int, Int) {
    return (a / b, a % b)
}

print(divmod(7, 3))
print(divmod(5, 2))
print(divmod(12,4))

没有下划线,我必须这样写以避免任何错误:

Without the underscores I have to write it like this to avoid any errors:

func divmod(a: Int, b:Int) -> (Int, Int) {
    return (a / b, a % b)
}

print(divmod(a: 7, b: 3))
print(divmod(a: 5, b: 2))
print(divmod(a: 12,b: 4))

我不明白这个下划线的用法.何时、如何以及为何使用这些下划线?

I don't understand this underscore usage. When, how and why do I use these underscores?

推荐答案

不同的用例有一些细微差别,但通常下划线表示忽略这个".

There are a few nuances to different use cases, but generally an underscore means "ignore this".

当声明一个新函数时,下划线告诉 Swift 参数在调用时不应该有标签——这就是你看到的情况.更完整的函数声明如下所示:

When declaring a new function, an underscore tells Swift that the parameter should have no label when called — that's the case you're seeing. A fuller function declaration looks like this:

func myFunc(label name: Int) // call it like myFunc(label: 3)

"label" 是一个参数标签,在调用函数时必须存在.(并且从 Swift 3 开始,默认情况下所有参数都需要标签.)name"是您在函数内部使用的该参数的变量名称.较短的形式如下所示:

"label" is an argument label, and must be present when you call the function. (And since Swift 3, labels are required for all arguments by default.) "name" is the variable name for that argument that you use inside the function. A shorter form looks like this:

func myFunc(name: Int) // call it like myFunc(name: 3)

这是一种快捷方式,可让您对外部参数标签和内部参数名称使用相同的词.相当于func myFunc(name name: Int).

This is a shortcut that lets you use the same word for both external argument label and internal parameter name. It's equivalent to func myFunc(name name: Int).

如果你想让你的函数在没有参数标签的情况下被调用,你可以使用下划线 _ 使标签成为空/忽略.(在这种情况下,如果您希望能够使用参数,则必须提供内部名称.)

If you want your function to be callable without parameter labels, you use the underscore _ to make the label be nothing/ignored. (In that case you have to provide an internal name if you want to be able to use the parameter.)

func myFunc(_ name: Int) // call it like myFunc(3)

在赋值语句中,下划线的意思是不赋值给任何东西".如果你想调用一个返回结果但不关心返回值的函数,你可以使用它.


In an assignment statement, an underscore means "don't assign to anything". You can use this if you want to call a function that returns a result but don't care about the returned value.

_ = someFunction()

或者,就像您链接到的文章一样,忽略返回元组的一个元素:

Or, like in the article you linked to, to ignore one element of a returned tuple:

let (x, _) = someFunctionThatReturnsXandY()

当你编写一个实现了一些已定义函数类型的闭包时,你可以使用下划线来忽略某些参数.


When you write a closure that implements some defined function type, you can use the underscore to ignore certain parameters.

PHPhotoLibrary.performChanges( { /* some changes */ },
    completionHandler: { success, _ in // don't care about error
        if success { print("yay") }
    })

同样,在声明一个采用协议或覆盖超类方法的函数时,可以使用_作为参数names来忽略参数.由于协议/超类也可能定义参数没有标签,因此您甚至可以以连续的两个下划线结束.

Similarly, when declaring a function that adopts a protocol or overrides a superclass method, you can use _ for parameter names to ignore parameters. Since the protocol/superclass might also define that the parameter has no label, you can even end up with two underscores in a row.

class MyView: NSView {
    override func mouseDown(with _: NSEvent) {
        // don't care about event, do same thing for every mouse down
    }
    override func draw(_ _: NSRect) {
        // don't care about dirty rect, always redraw the whole view
    }
}

与后两种风格有些相关:当使用绑定局部变量/常量的流控制构造时,您可以使用 _ 忽略它.例如,如果您想在不需要访问其成员的情况下迭代一个序列:


Somewhat related to the last two styles: when using a flow control construct that binds a local variable/constant, you can use _ to ignore it. For example, if you want to iterate a sequence without needing access to its members:

for _ in 1...20 { // or 0..<20
    // do something 20 times
}

如果您在 switch 语句中绑定元组大小写,则下划线可以用作通配符,如本例所示(从 Swift 编程语言):

switch somePoint { // somePoint is an (Int, Int) tuple
case (0, 0):
    print("(0, 0) is at the origin")
case (_, 0):
    print("(\(somePoint.0), 0) is on the x-axis")
case (0, _):
    print("(0, \(somePoint.1)) is on the y-axis")
default:
    print("(\(somePoint.0), \(somePoint.1)) isn't on an axis")
}

最后一件事不太相关,但我将包括在内,因为(如评论所述)它似乎将人们引向此处:标识符的下划线 - 例如var _foofunc do_the_thing()struct Stuff_ —— 对 Swift 没有什么特别的意义,但在程序员中有一些用途.


One last thing that's not quite related, but which I'll include since (as noted by comments) it seems to lead people here: An underscore in an identifier — e.g. var _foo, func do_the_thing(), struct Stuff_ — means nothing in particular to Swift, but has a few uses among programmers.

名称中的下划线是一种样式选择,但在 Swift 社区中不是首选,Swift 社区对类型使用 UpperCamelCase 和所有其他符号使用 lowerCamelCase 有很强的约定.

Underscores within a name are a style choice, but not preferred in the Swift community, which has strong conventions about using UpperCamelCase for types and lowerCamelCase for all other symbols.

使用下划线对符号名称进行前缀或后缀是一种样式约定,历史上用于区分私有/仅供内部使用的符号与导出的 API.然而,Swift 有访问修饰符,所以这个约定在 Swift 中通常被视为非惯用语.

Prefixing or suffixing a symbol name with underscore is a style convention, historically used to distinguish private/internal-use-only symbols from exported API. However, Swift has access modifiers for that, so this convention generally is seen as non-idiomatic in Swift.

一些带有双下划线前缀的符号 (func __foo()) 潜伏在 Apple SDK 的深处:这些是使用 NS_REFINED_FOR_SWIFT 导入到 Swift 中的 (Obj)C 符号代码>属性.Apple 在他们想要制作 (Obj)C API 的更快速"版本时使用它——例如,将类型无关的方法变成通用方法.他们需要使用导入的 API 来使精炼的 Swift 版本正常工作,因此他们使用 __ 使其可用,同时将其隐藏在大多数工具和文档中.

A few symbols with double-underscore prefixes (func __foo()) lurk in the depths of Apple's SDKs: These are (Obj)C symbols imported into Swift using the NS_REFINED_FOR_SWIFT attribute. Apple uses that when they want to make a "more Swifty" version of an (Obj)C API — for example, to make a type-agnostic method into a generic method. They need to use the imported API to make the refined Swift version work, so they use the __ to keep it available while hiding it from most tools and documentation.

这篇关于为什么我需要快速下划线?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 23:56