Anonymous function with no curly braces and no argument labels?

swift pass function as parameter
argument label swift
swift default parameter
swift inout
swift nested functions
lambda functions swift
swift function type
swift implicit return

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 = (+)

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?

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?

Actually, this is no shorthand.

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:

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: >)

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

Arrow functions, the basics, If there are no arguments, parentheses will be empty (but they should be present​): Arrow functions can be used in the same way as Function  An anonymous function is a function that is not stored in a program file, but is associated with a variable whose data type is function_handle. Anonymous functions can accept multiple inputs and return one output. They can contain only a single executable statement. For example, create a handle to an anonymous function that finds the square of

+ is an infix operator and a function name in Swift. There are many such functions defined on many types (it is overloaded).

You can define + for your own custom type. For example:

struct Foo {
    var value: Int

    static func +(_ lhs: Foo, _ rhs: Foo) -> Foo {
        return Foo(value: lhs.value + rhs.value)

var f1 = Foo(value: 5)
var f2 = Foo(value: 3)

let f3 = f1 + f2
print(f3.value) // 8

This works:

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

because the signature of the + function has been fully specified, so Swift is able to identify the correct + function.

And if we want to assign our new + function to plus:

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

It's really no different than this:

func add(_ a: Int, _ b: Double) -> Double {
    return Double(a) + b

let plus: (Int, Double) -> Double = add

print(plus(3, 4.2))  // 7.2

So why the parentheses? Why specify (+) instead of just +?

+ is also a unary operator in Swift.

For example, you can say:

let x = +5

So just trying to say:

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

confuses the compiler because it is treating the + as a unary prefix operator and it is expecting the + to be followed by something else such as 5. By surrounding it with parentheses, the Swift compiler then stops trying to parse + as a unary operator and treats is just as its function name. Even if + weren't a unary prefix operator, Swift would still be expecting values on either side of the +, so the parentheses tell Swift that you aren't providing any inputs to the function, but just want the function itself.

You can refer to the + function without the parentheses in situations where it isn't ambiguous. For example:

var arr = [1, 2, 3]
let sum = arr.reduce(0, +)

Functions, single unnamed parameter to a complex function with expressive parameter names Here's a function with no input parameters, which always returns the same String person and a Bool argument value labeled alreadyGreeted in parentheses, By default, parameters use their parameter name as their argument label. JavaScript: Normal, Anonymous, and IIFE Functions. The function name is camelCase. Curly braces are necessary when defining this type of function, it is the body of the function which is where

(+) by itself is an operator method. You can declare your own operator like this:

precedencegroup CompositionPrecedence {
    associativity: left
    higherThan: AssignmentPrecedence

infix operator •: CompositionPrecedence

func •(a: Int, b: Int) -> Int {
    return a + b

Usage will be the same:

var closure: (Int, Int) -> Int = (•)
print("\(closure(1, 2))")

Anonymous functions in Swift, An anonymous function is a function definition that is not bound to an identifier. parameter list and return type as the first thing inside the curly braces, and then put just the anonymous function body without a label (this is  Otherwise, keep the braces and use a return statement. 8.4 If your function takes a single argument and doesn’t use braces, omit the parentheses. Otherwise, always include parentheses around arguments for clarity and consistency. Example of good anonymous arrow callback.

Swift Essentials: Closures, Learn the basics about using closures in the Swift programming language. An unnamed closure is created inline, and is not defined with a keyword. after the function call's parentheses, and you omit the argument label for  standard allows me to omit pointless curly parentheses around arrow function bodies, but forces me to include pointless parentheses around unary arrow functions I just don't get the reasoning, if it was to improve readability then from my subjective point of view and speaking on behalf of other developers I know this rule has failed, but hey

Lambda in Kotlin - Samira Badamestani, invocation.Lambdas Expressions are essentially anonymous functions that… Inside curly braces first you specify the parameters, then the arrow, then the lambda body. There must be no white-space between return and label name. An anonymous function is a set of related statements that is assigned a name. return A(n) ____ statement is a statement that returns a value to the statement that called the function.

Recent Developments in Decision Support Systems, An element of a variant type is a labeled expression, where the label is one of A function can be defined in the language using the lambda expression of the form: fun (x : T). e., where x is the parameter of the function whose type is T, and where e is an The language does not allow recursive type or function definitions. A higher-order function is a function that takes functions as parameters, or returns a function. A good example is the functional programming idiom fold for collections, which takes an initial accumulator value and a combining function and builds its return value by consecutively combining current accumulator value with each collection element

  • I'm not even sure if "explain why" questions should be asked on Stackoverflow.
  • @kelin, most questions are of the 'explain why this doesn't work' or 'explain how I can accomplish this' nature. While this might solve an immediate need, the larger benefit is that knowledge is added to the tool-box—knowledge that makes one a better programmer and can be used again and again. That's why I asked the question—because I saw something in your code that I thought I might be able to learn from and possibly employ in future.
  • Thanks for a great explanation Jörg. I've done a little bit of Ruby coding, so I'm familiar with + being a method name. It just didn't occur to me that this odd looking (+) could be the same kind of thing in Swift. In Ruby, the mechanics are clear when you write 1.+(2) and get 3—essentially + is an instance method of the Integer class. The above quote kind of implies that + is a method of Swift's Integer type, but neither of the following work (with or without brackets): 1.(+)(2) or Int.(+)(1, 2). I notice however that (+)(1, 2) does work. Thanks again!
  • Yes, Swift doesn't let you refer to the function as Int.+ or Int.(+). Members accessed with . notation have to begin with a letter or _. The operator methods are special in that they use special symbols, but then the compiler expects you to use them inline 3 + 4. (+)(3, 4) works because as we mentioned before (+) does specify a function when the types are specified (or can be inferred as in this case).
  • Ahhh... the detective at his finest. :') Always a pleasure reading your answers. :'D I don't even know why i bother answering when i know that you'll come around sooner or later and deliver. sigh
  • Thanks for a great explanation vacawama. (See also my comment on Jörg's answer.)
  • Thanks for the succinct answer Bohdan. So really, I was asking the wrong question! (not an anonymous function at all)