Feb '23 It took a bit for me to write up a solution for checkpoint 5, however i've got a slight problem. here's one of my attempts. ``````let unluckyNumbers = { (evenNumbers: [Int]) -> [Int] in for _ in luckyNumbers { luckyNumbers.filter { !\$0.isMultiple(of: 2) } .sorted() .map { print("\(\$0) is a lucky number") } } return evenNumbers } unluckyNumbers(luckyNumbers)`````` this prints the proper result 10 times, and i'm not sure why. is there way to only print the resulting array once? thanks 2 Feb '23 First of all why do you need return array of integers? filter, sort, and map already "handling" values by themsevles. You don't need to loop over in this case. ``````let luckyNumbers = [7, 4, 38, 21, 16, 15, 12, 33, 31, 49] luckyNumbers.filter { !\$0.isMultiple(of: 2) }.sorted().map { print("\(\$0) is a lucky number") }`````` you can just put everything in one line 3 Feb '23 I returned an array because the final step was for me to print the resulting array after mapping it to the above string. What you posted above was my first attempt but I didn't seem right to me. ``let unluckyNumbers = luckyNumbers.sorted().filter { !\$0.isMultiple(of: 2) }.map{"\(\$0) is a lucky number"}`` The challenge mentioned using closures as part of the solution. If I remove the for loop I do get the proper result printed once. I should've just went with that one liner instead of questioning myself. Maybe I over thought this problem too much. Thank you though. 3 Feb '23 If you wanted to print array of strings then you can do as follows ``````let luckyNumbers = [7, 4, 38, 21, 16, 15, 12, 33, 31, 49] var array = luckyNumbers.filter { !\$0.isMultiple(of: 2) }.sorted() var strArray: [String] = [] for num in array { strArray.append("\(num) is a lucky number") } print(strArray) //or if you want oneliner var stringArray = luckyNumbers.filter { !\$0.isMultiple(of: 2) }.sorted().map { String(\$0) + " is a lucky number" } print(stringArray) `````` as for closures filter, sort and map, they work with closures already so there is no need to create your own From Apple Documentation -> Declaration `func filter(_ isIncluded: (Self.Element) throws -> Bool) rethrows -> [Self.Element]` Parameters isIncluded A closure that takes an element of the sequence as its argument and returns a Boolean value indicating whether the element should be included in the returned array. 2

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

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.

You are not logged in