What are Closures in Swift 3? (Part 2)
In the last post I wrote about what closures are and some use of them now I want to cover about some important characteristics of closures and these are:
- Inferring Type from Context
- Implicit Return from Single-Expression Closures
Let’s tackle one at a time.
Inferring Type from Context
We have this function:
sayHello
method accepts a String and a Closure on its parameters and we call it in this way:
But since it is already known that the type expected of the Closure argument will be (String) -> Void
, we could only remove the types of the argument and the type of return like this:
You see the difference? We removed the type String
of person
and also the returning type it happens to be Void
.
Implicit Return from Single-Expression Closures
In the following code I’m filtering the zeros from the array.
Swift allows us to remove the keyword return
when we have a single expression like in the example above, we’re only doing a single thing that’s returning something.
And Swift already knows that the returning type of the closure will be a Bool
, filter
method expects a Closure like (Int) -> Bool
, and the call is reduced like this:
Hope you find it useful this quick view of Closures so there will be a last post about some other characteristics of Closures that I saw are important but I will reserve that for another post.
Thanks for reading me!