Swift Closures Syntax

Swift Closures Syntax

We all have a bad memory when it comes to specific syntax of Closure. At least this post is going to help me, throwing out there if someone else can be benefited by it. Happy Sw...

Alok Choudhary
Austin, TX
2 min read

We all have a bad memory when it comes to specific syntax of Closure. At least this post is going to help me, throwing out there if someone else can be benefited by it. Happy Swifting

As a variable:

[swift] var closureName: (ParameterTypes) -> (ReturnType) [/swift]

As an optional variable:

[swift] var closureName: ((ParameterTypes) -> (ReturnType))? [/swift]

 

As a type alias:

[swift] typealias ClosureType = (ParameterTypes) -> (ReturnType)[/swift]

As a constant:

[swift] let closureName: ClosureType = { … } [/swift]

As an argument to a function call:

[swift] funcName({(ParameterTypes) -> (ReturnType) in statements}) [/swift]

As a function parameter:

[swift] array.sort({ (item1: Int, item2: Int) -> Bool in return item1 < item2 }) [/swift]

As a function parameter with implied types:

[swift] array.sort({ (item1, item2) -> Bool in return item1 < item2 }) [/swift]

As a function parameter with implied return type:

[swift] array.sort({ (item1, item2) in return item1 < item2 }) [/swift]

As the last function parameter:

[swift] array.sort { (item1, item2) in return item1 < item2 } [/swift]

As the last parameter, using shorthand argument names:

[swift] array.sort { return $0 < plain } [/swift]

As the last parameter, with an implied return value:

[swift] array.sort { $0 < plain } [/swift]

As the last parameter, as a reference to an existing function:

[swift] array.sort(<) [/swift]

As a function parameter with explicit capture semantics:

[swift] array.sort({ Plain Text>Plain Text>[unowned self] (item1: Int, item2: Int) -> Bool in return item1 < item2 }) [/swift]

As a function parameter with explicit capture semantics and inferred parameters / return type:

[swift] array.sort({ [unowned self] in return $0 < plain }) [/swift]

Link copied to clipboard!

Made with ❤️ in Austin.

Copyright © 2026