BLACK FRIDAY SALE: Save big on all my Swift books and bundles! >>

SOLVED: Checkpoint 5 - turn it into one function with functions inside?

Forums > 100 Days of SwiftUI

I solved Checkpoint 5, but how can I solve by making one fuction with this all inside of it? I think I heard Paul say try not to use a bunch of temporary variables, right?

let luckyNumbers = [7, 4, 38, 21, 16, 15, 12, 33, 31, 49]
let oddOnly = luckyNumbers.filter { $0 % 2 != 0 }
let sortedOdds = oddOnly.sorted()
let mapToString = sortedOdds.map { print("\($0) is a lucky number") }

1      

You are curious and asking the right questions! This is a huge step towards mastering SwiftUI.

You don't want us to give you the answer, but we can lead you in the right direction.

The Swift language is heavily typed. One of the early skills you develop should be to identify or ask XCode to tell you what type a variable is.

For example:

let firstName = "michael"

What type is this? You and I can easily see it's a string. But if you hover your mouse over firstName while holding down the option key, your cursor turns into a question mark. Click the variable name. Swift will then confirm firstName is of type String. Get used to doing this with all your variables. Do it a lot!

Next get comfortable with the idea that Swift types (Integers, Doubles, Arrays, etc.) have methods. There are too many methods to memorize in your first 100 days of Swift. Get comfortable with looking up method names in Apple's documentation.

Next get comfortable with the idea that type methods work on types, not variables! See if the following example makes sense to you?

let firstname = "michael"
print ( firstname.uppercased() )  // method applied to a variable of type String
//
print( "michael".uppercased() )  // method applied directly to a type.   

What methods can you call on an array of Integers? You have several in your code snip above. You've used filter, sorted, and map methods. Each of these methods work with an array of Integers. (Type = [Int] that is, an array of Integers)

Now, the last step. Get comfortable with chaining functions together.

When you filter lucky numbers, Swift returns an array of Integers. Well you know you can sort an array of integers, so just add the sorted() method.

let luckyNumbers = [7, 4, 38, 21 ]     // This is an array of integers.
    luckyNumbers.filter { $0 % 2 != 0 }     // So is this!  
// This whole line is really an "array of Integers"
// It looks like you're filtering the *previous* array of Integers. 
// But Swift performed the closure and
// returned a new array of Integers to you.

The sorted function works on an array of integers, so you can add another function to the returned results.

let luckyNumbers = [7, 4, 38, 21 ]     // This is an array of integers.
let _ =    luckyNumbers.filter { $0 % 2 != 0 }     // So is this!  This whole line is really an "array of Integers"
//         ====================================
//  Think to yourself, "This underlined bit is just an array of integers."
//
let _ = luckyNumbers.filter { $0 % 2 != 0 }.sorted()
//  Think to yourself, "I am just sorting an array of integers."

To be honest, I write out my code just as you did. First to get it working. After it works, I see if I can reduce multi-line complexity.

You can see a pattern in your code. You perform a simple function on an array of Integers. You give the results a simple name. Then you use that new variable in the very next line; often that's the LAST TIME you use that variable.

When you see that pattern, ask yourself if you can just copy/ paste the function into one line, and skip over the whole "create a new, temporary variable" step.

let luckyNumber = [5, 7, 12, 6, 100, 3]  // some array
let finalVariable = luckyNumber.sorted().reversed().filter{ $0.isMultipleOf: 2}.last // chained 4 functions!
//  What type is finalVariable?  

2      

Extra Credit Challenge

Here's another challenge for you. Use as many temporary variables as you need to get this to work. Then figure out how to chain the methods together. Can you find the solution with one line of code?

Practice determining what the types are. Also, you may have to look in Apple's documentation for helpful methods.

Here's a string

let homework = "I ❤️ HackingWithSwift.com"
let heart = << YOUR CODE HERE >>

Use three methods to isolate the heart character.

Do not use String's substring function.

Please write your answer below!

2      

Hi @michaelpgalen

You can havve mutliple function on a variable

So will give the result only odd numbers in the same order.

let result = luckyNumbers.filter { $0 % 2 != 0 } 
// This can done using .filter { $0.isMultiple(of: 2) == false }

Add .sorted() give them in ascending order

let result = luckyNumbers.filter { $0 % 2 != 0 }.sorted()

Add .map to transform to string array

let result = luckyNumbers.filter { $0 % 2 != 0 }.sorted().map { "\($0) is a lucky number" }

To print you need to go over the array

for item in result {
    print(item)
}

However there is a function .forEach

let result = luckyNumbers.filter { $0 % 2 != 0 }.sorted().map { "\($0) is a lucky number" }.forEach { print($0) }

However as this is very long and hard to read you will see people tend to put each one on different lines but still is the same function call

let result = luckyNumbers
    .filter { $0 % 2 != 0 }
    .sorted()
    .map { "\($0) is a lucky number" }
    .forEach { print($0) }

3      

Thank you so much for the help @NigelGee and @Obelix !! That all makes a lot of sense.

let luckyNumbers2 = [7, 4, 38, 21, 16, 15, 12, 33, 31, 49]
let result2 = luckyNumbers2.filter {$0 % 2 != 0}
    .sorted()
    .map {"\($0) is a lucky number"}
    .forEach { print($0)}

1      

https://www.hackingwithswift.com/forums/100-days-of-swiftui/checkpoint-5-turn-it-into-one-function-with-functions-inside/11073/11080

@obelix - thanks for the extra credit challenge. It was helpful to dig in more to chaining methods.

let homework = "I ❤️ HackingWithSwift.com"
let heart = homework.sorted().suffix(1)

print(heart)

1      

Since I did checkpoint 5 again yesterday and I came across this I thought I'd give the extra credit challenge a shot. This worked for me but I'm wondering what Obelix had planned for his solution.

let homework = "I ❤️ HackingWithSwift.com"
let heart = homework.dropFirst(2).dropLast(21)
print(heart)
// Prints - ❤️

1      

@michaelpgalen and @vtabmow

Well done! I think I had the first solution in mind, sorting then grabbing the first character. But well done for thinking out of the box by using dropFirst and dropLast.

To be honest, those two methods weren't in my toolbox! I've never used them before.

Well done!

2      

I was able to finish this but getting () at the end of the print statements.

7 is a lucky number
15 is a lucky number
21 is a lucky number
31 is a lucky number
33 is a lucky number
49 is a lucky number
()

   

Hacking with Swift is sponsored by RevenueCat

SPONSORED In-app subscriptions are a pain to implement, hard to test, and full of edge cases. RevenueCat makes it straightforward and reliable so you can get back to building your app. Oh, and it's free if your app makes less than $10k/mo.

Learn 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.