Swift’s closure is an anonymous function, think of it as a function that can be declared as a property or parameter.

It’s easy to use, just like Objective-C and Kotlin.

funcName() { (parameter) -> returnType in
    // Processing logic...
}

Refer here: https://fuckingclosuresyntax.com

Here’s a little example:

When calling an API, you will typically do so through a function. Within this function, you will always call the API asynchronously. Afterward, you will need to wait for the asynchronous task to complete. Once it does, the callback will take over and continue the next task.

func apiCall(completion: ((Int)->Void)?) {
  DispatchQueue.main.async {
    // This optional variable completion: ((Int)->Void)? is a closure.
    print("Closure Demo", "Api calling")
    completion?(2)
  }
}

Calling it:

self.apiCall(completion: { value in
  print("Closure Demo", value)
})

Or use it as a trailing closure. When your closure is the last parameter, nothing changes, it’s just for code aesthetics.

self.apiCall() { value in
  print("Closure Demo", value)
}

Console print:

Closure Demo Api calling
Closure Demo 2

As a higher-order function, closures are frequently used to determine the result of a value. Familiarize yourself with closures as much as possible to make your code neater and more readable.