|
In this checkpoint I have to create a function that finds the square root of a number and returns it without using sqrt() or similar methods. As per the hint in the course, I brute forced all the possible square roots with a for loop that checks if the input is equal to i * i and then breaks if it gets a match. But I can't figure out how to return the value of 'i' as an integer in the function. Would appreciate any help.
|
|
Found a workaround! It's not perfect but the code runs correctly.
The only problem I see is throwing the numberError.noRoot. Is there a more elegant way to do this? If I put it in the loop as an 'else' it would just throw an error after the first iteration if the square root isn't 1. |
|
You can just return As for throwing |
|
Instead of break
and delete
|
|
Wow! It was so easy. For some reason when I tried returning i inside the loop Xcode complained so I just gave up on it. Thanks for the help! |
|
|
|
the return i doesnt make the program out of the loop, it still doing the loop until reach 100. For me I prefer with break inside the loop so the program dont waste any more time. |
|
Change the
and you will see that the loop only runs 10 times before hitting a match and causing the function to return.
|
SAVE 50% All our books and bundles are half price for Black Friday, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.
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.