|
So, it took me a couple of days to come up with this solution for Checkpoint 5:
This prints out:
So technically it works but the code inside the closure looks disorienting and I have a feeling that I'm missing something. Am I even doing this right? Thanks for any tips. |
|
Welcome to Checkpoint 5! That disoriented feeling you have is the direct result of declarative programming! It can be dizzying! You created solve to be a function that takes an array of [Int] and returns nothing. Was this your intention? Another way to complete this checkpoint would be to create a computed property that does the same as your function.
This solution uses slightly less code, but can't be used a function. Your code get full marks for being swifty, one line of code, and declarative! Well done. |
|
It was the only way I could wrap my head around the whole thing at this point. :D I also tried to make it return a String but couldn't get it working...
I'll have to play around with this technique. Thanks for the example and encouragement! |
|
Oh, and another thing: Let's assume I want to use solve for another array. Now it exclusively filters luckyNumbers. Could I achieve this by changing luckyNumbers.filter to just .filter and then calling solve(someOtherNumbers)? |
|
Not quite. You did have one bug in your code. You wrote:
Run this in your playground:
Both will provide the same result! Why? Because you HARD coded the array name into your filter statement. In the second line, your function accepts the array of [ 9, 99, 199, 999, 42], but ignores it. To analyze different arrays of ints, you'll need to change your function's signature.
|
|
Ah, I see. I don't quite understand _ yet so I'll have to be careful with it. But the hardcoded array was something I actually noticed by myself and that's what led me to wonder the syntax. So maybe I should frame the actual question differently. Let's say I start with
like in your second example. Whether I then pass in luckyNumbers or someOtherNumbers or moreNumbers etc. when calling solve(numbers: someNumbers), can I still format the code like in your first example, beginning the function chain inside solve with just .filter instead of numbers.filter? I'll play around with this in Xcode after I've had my coffee. :D |
|
In Playgrounds (you ARE using playgrounds, yes?!) press the option key then hover your mouse over the variable named solve. Swift will tell you what solve is.
|
SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.
Sponsor Hacking with Swift and reach the world's largest Swift community!
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.
Link copied to your pasteboard.