WWDC22 SALE: Save 50% on all my Swift books and bundles! >>

Day 15 of 100 Day Challenge

Forums > 100 Days of Swift

Well, I finished Day 15 of the 100 Day Swift Challenge. It was -- as will the next two following days -- a review day, which is great, because I need to review optionals and closures.

All seems to be going well and I look forward to progressing.


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!


Hacking with Swift is sponsored by Emerge

SPONSORED Why are Swift reference types bad for app startup time, and what’s the performance cost of protocol conformances? That’s just a couple of the topics you can learn about on the Emerge blog — written by the app performance experts behind Emerge’s advanced app optimization and monitoring tools, based on their experience of working at companies like Apple, Airbnb, Snap, and Spotify.

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

Unknown user

You are not logged in

Log in or create account

Link copied to your pasteboard.