@andreaSara wonders about closures:
Can somebody explain me the purpose of the following code in Bucketlist?
var onSave: (Location) -> Void
Patrick provides the correct answer! But I'd like to add some commentary.
In programming languages everyone seems comfortable with variables that hold Integers, Doubles, Strings
, and Booleans
. If you have the following code in your program, no one thinks twice about what you've declared:
// This is standard stuff in Swift and other languages
let favoriteSinger = "Taylor Swift" // <- Store a string
let favoriteNumber = 42 // <- Store an integer
let thisIsNotPi = 3.1512929 // <- Store a double
let isContrivedExample = true // <- Store a boolean
let famousProgammers: [Programmer] // <- Store a collection of programmer objects
But the line you quote above gives new programmers absolute fits! Why?
I think it's because new programmers are NOT comfortable with the concept that Swift allows variables to hold more than just standard data and arrays.
Store a what?
The onSave
variable in your example doesn't hold a boolean
. It doesn't hold a string
. What does it hold? It's a strange concept to many, but the code is telling Swift that the variable onSave
holds a function! Moreover, the code says the function has a specific function signature. This signature requires the function to consume a Location
object (defined somewhere else...). AND the function doesn't return any value when it completes its work.
What does the function do?
We don't know and we don't care.
As long as you provide a function that accepts a Location
and returns nothing, the variable onSave
can hold your function. It's similar to how a variable that holds an Integer
can hold a 42, a 0, or 1_000_042. The only requirement is the number must be an integer
.
onSave
doesn't care what function you provide. The only rule is the function must consume a Location
, and it must not return any other value.