没有花括号和没有参数标签的匿名函数? [英] Anonymous function with no curly braces and no argument labels?
问题描述
我在另一个问题上看到了一些代码,该代码似乎创建了具有某些异常语法的匿名函数(闭包表达式):
I saw some code on another question that seems to create an anonymous function (closure expression) with some unusual syntax:
let plus: (Int, Int) -> Int = (+)
我了解左侧-它声明了类型为(Int, Int) -> Int
的常量(该函数接受两个Integer,并返回一个Integer).但是什么是(+)
?如何声明没有花括号的函数?在没有任何类型的参数标签的情况下如何引用两个参数?
I understand the left side—that it's declaring a constant of type (Int, Int) -> Int
(a function that takes two Integers and returns an Integer). But what is (+)
? How can it declare a function without curly brackets, and how does it refer to the two arguments when there are no argument labels of any kind?
该函数接受两个参数,将它们加在一起,然后返回结果.如果将+
运算符替换为其他运算符(例如*
),则操作会更改.那么{$0 + $1}
的某种速记形式吗?如果是这样,此速记背后的逻辑是什么?
The function takes two arguments, adds them together, and returns the result. If I replace the +
operator with a different one (say a *
), the operation changes. So is it some kind of shorthand for {$0 + $1}
? If so, what is the logic behind this shorthand?
推荐答案
实际上,这不是速记.
plus
是类型(Int, Int) -> Int
的变量.您可以为其分配任何该类型(或其任何子类型)的对象.文字lambda闭包肯定是这种类型的,但是实际上,命名函数或方法也可以.而这正是这里发生的事情.
plus
is a variable of type (Int, Int) -> Int
. You can assign it any object that is of this type (or any of its subtypes). A literal lambda closure is certainly of this type, but actually a named function or method would also do. And that is exactly what is happening here.
它正在将名为+
的运算符方法对象分配给该变量.
It is assigning the operator method object named +
to the variable.
This is mentioned sort-of implicitly in the Closures chapter of the language guide:
操作员方法
实际上,甚至还有一种更短的方式来编写上面的闭包表达式. Swift的
String
类型将其大于字符串运算符(>
)的特定于字符串的实现定义为一种方法,该方法具有两个类型为String
的参数,并返回类型为Bool
的值.这与sorted(by:)
方法所需的方法类型完全匹配.因此,您只需传递大于号运算符,Swift便会推断您要使用其特定于字符串的实现:
Operator Methods
There’s actually an even shorter way to write the closure expression above. Swift’s
String
type defines its string-specific implementation of the greater-than operator (>
) as a method that has two parameters of typeString
, and returns a value of typeBool
. This exactly matches the method type needed by thesorted(by:)
method. Therefore, you can simply pass in the greater-than operator, and Swift will infer that you want to use its string-specific implementation:
reversedNames = names.sorted(by: >)
因此,代码正在执行的操作是将操作员方法+
分配给变量plus
. +
只是分配给变量的函数的名称.没有魔术速记.
So, what the code is doing is assigning the Operator Method +
to the variable plus
. +
is simply the name of the function assigned to the variable. No magic shorthand involved.
看到这个消息你会感到惊讶吗?
Would you be surprised to see this?
let plus: (Int, Int) -> Int = foo
这篇关于没有花括号和没有参数标签的匿名函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!