In this post I will talk about Swift closure: what they are and their syntax.
As reported on the official Apple swift documentation closures are:
Closures are self-contained blocks of functionality that can be passed around and used in your code. They can capture and store references to any constants and variables from the context in which they are defined.
Closures are in many ways what blocks are in Objective-C (or lamba function in other languages).
As it was for blocks, it is not easy to remember their syntax. This post is intended to be a reference for me (and you, readers ) about closure syntax. You could also take a look at F$%&£&g closure syntax.
Declared as a variable (valid also for let
constants):
var closure: (parameters) -> returnType
Declared as an optional variable:
var closure: ((parameters) -> returnType)?
Declared as a type alias:
typealias ClosureType = (parameters) -> returnType
Declared as a function parameter and then call that function:
func myFunction(closure: (parameters) -> returnType) {
...
}
...
/** You can explictly write the type of parameters. **/
//Call with round brackets.
myFunction(closure: { (parameters) -> returnType in
...
})
//Call without round brackets (only if closure is the last parameter).
myFunction { (parameters) -> returnType in
...
}
There is also the possibility to use a shorthand for the parameter: you can call them using $
followed by the index
of the argument in the call. Last but not least, you can capture self and avoid retain cycle using [unowned self]
before the parameters. Go and show to the world the power of closure in Swift!!
During the last months I worked a lot with Spring Boot backend applications. In this post I explain how you can consume a REST api from a Spring Boot application using RestTemplate and (the new) WebClient.
Read MoreRecently I upgraded my ID3TagEditor swift package to the latest Swift tools version (5.3). During the upgraded I discovered that now you can bundle reources with your Swift package. In this post I will show you how you can do this, and also a interesting trick in order to be able to build a project as a Swift Package and as a standard project from Xcode.
Read MoreRecently I migrated my website to Webpack and TypeScript. I decided also to give a try to Workbox, a set of Google libraries to improve the creation of a Progressive Web App. Let’s see how easy it is to create a PWA with this tools.
Read More