|
I was experimenting with functions trying to understand them better and I've created function like this for checkpoint 4: import UIKit func SquareRootThisNumber (_ number: Int) {
} SquareRootThisNumber(25) I was only experimenting I know the two better solutions for this problem but if I would write this function myself I would write it probably like this... This code looks littlebit cleaner then throwing functions and creating do try catch block, but are there reasons why should I not use this code I have few in my mind but I would like to hear yours opinion. |
|
Nice! The code that you made yourself is always a step forward in your learning curve, especially if it works and shows the result. Just a small note, you might think about efficiency of code as well. Also in Swift it is a convention to give a name to the functions with no capital letter. In your code if you try to find square root of 10_000, loop will run so many times to find the result... mmmm maybe there is a more better solution to this... but in any case your code works and you find the solution yourself, which is really wonderful and this is how we all learn something new. So keep coding!!!
|
|
The biggest one in my mind (ignoring that the whole point of Checkpoint 4 is to learn about throwing functions) is that this function really doesn't do anything. Sure, it prints out the square root of the given number, but so what? It's far more useful if it returns the square root and then the code calling the function can actually do something with the result. And for that, a throwing function is your best bet. You could return some magic value (e.g., returning And just because a function throws, you don't necessarily have to use a |
|
Could someone check my code, please?
|
|
Keep in mind, this exercise is meant to get you to think logically, with a focus on throwing functions. At this point in your journey, you're not expected to write A-Level code. This code below works! But, it's not very Swifty! That is, there's probably some syntax, or programming structure that you could use that's easier to read. This is very reminiscent of an old school basic program. Can you find another way?
|
|
|
|
Note: @ygeras provided sample code. This just expands the explanation. In your code, you have three lines to set the starting value, evaluate the ending condition, and to increment the counter. This provides potentially three places where you can have a syntax or logic error.
A more Swifty way would use a (I pulled the code out of the throwing function just to demonstrate the loop. Run this in Playgrounds.)
|
SPONSORED Get accurate app localizations in minutes using AI. Choose your languages & receive translations for 40+ markets!
Sponsor Hacking with Swift and reach the world's largest Swift community!
You need to create an account or log in to reply.
All interactions here are governed by our code of conduct.
Link copied to your pasteboard.