UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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.

3      

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!

3      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

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

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.