swift - 没有花括号和参数标签的匿名函数?

标签 swift lambda anonymous-function shorthand

我在 another question 上看到了一些代码这似乎用一些不寻常的语法创建了一个匿名函数(闭包表达式):

let plus: (Int, Int) -> Int = (+)

我理解左侧 — 它声明了一个 (Int, Int) -> Int 类型的常量(一个接受两个整数并返回一个整数的函数)。但是什么是 (+)?它如何声明一个没有大括号的函数?当没有任何类型的参数标签时,它如何引用两个参数?

该函数接受两个参数,将它们相加,然后返回结果。如果我将 + 运算符替换为不同的运算符(比如 *),操作就会改变。那么它是 {$0 + $1} 的某种简写吗?如果是这样,这个简写背后的逻辑是什么?

最佳答案

实际上,这不是简写。

plus(Int, Int) -> Int 类型的变量。您可以将任何属于此类型(或其任何子类型)的对象分配给它。文字 lambda 闭包当然是这种类型,但实际上命名函数或方法也可以。而这正是这里正在发生的事情。

它正在将名为+ 的运算符方法对象分配给变量。

这在 Closures chapter of the language guide 中隐含地提到了:

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 type String, and returns a value of type Bool. This exactly matches the method type needed by the sorted(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+ 只是分配给变量的函数的名称。不涉及魔术速记。

看到这个你会不会很惊讶?

let plus: (Int, Int) -> Int = foo

关于swift - 没有花括号和参数标签的匿名函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52093049/

相关文章:

c# - Lambda 表达式,如何在对象内部进行搜索?

python - 使用 Zappa 配置 AWS Lambda 函数,出现未知错误

java - 等效于 Java 中的 C# 匿名方法?

scala - Scala 如何实现从表达式中返回?

swift - 似乎无法将框架导入 Xcode 10.2.1 中的当前项目

Xcode 7.3.1 在启动屏幕上崩溃 : Library not loaded

swift 3 : Be able to tap view behind a collectionViewCell?

ios - 只在某些特定的 ViewController 中启用横向

具有宽松类型要求的 C++17 lambda 捕获

java - 等待 Async Volley 请求的结果并返回它