我在 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 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
。 +
只是分配给变量的函数的名称。不涉及魔术速记。
看到这个你会不会很惊讶?
let plus: (Int, Int) -> Int = foo
关于swift - 没有花括号和参数标签的匿名函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52093049/