It was hard to wrap my head around closures. All my previous programming courses taught me variables held primitives such as Bool, Int, Double, String.
Assigning a function to a variable? Ouch!
To help cement this concept I added a few notes to my 100 Days Playground notebook. Maybe this helps you?
This helped me accept the strangeness of defining a variable that holds a function.
An Integer variable doesn't really care if it holds a 9 or a 42, it just has to be an Integer.
A variable that holds a function doesn't care what the function does, it just has to obey the function's signature.
Here's a snip that helped me.
// Closure 1: a function that takes a String and returns an Integer
let countChars = { (input: String) -> Int in input.count } // how many characters are in the input string
// Closure 2: a function that takes a String and returns an Integer
let almostRandom = { (input: String) -> Int in
input.count + Int.random(in: 1...4) // somewhat random number based on number of characters in the string
}
// someFunction is a variable. not an Int, or a String, or a Bool
// someFunction must hold a function!
// Don't care what the function does.
// BUT the function must take a String and return an Integer.
var someFunction: (String) -> Int
someFunction = countChars // doesn't care what the function does
someFunction("hello from someFunction") // 23
someFunction = almostRandom // same. doesn't care.
someFunction("hello from someFunction") // 24, 25, 26 or 27
Well done on reaching Day 15!