## Checkpoint 4

 Apr 22 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) { ``````switch number { case 1...10_000: for i in 1...100 { if number == i * i { print("The squared \(number) is \(i)") return } } print("\(number) is not a perfect square between 1 and 10_000") default: print("You are out of the loop") }`````` } 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. Apr 22 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!!! ``````func squareRootThisNumber (_ number: Int) { switch number { case 1...10_000: for i in 1...100 { print(i) // see the print console and how many times code runs to get to the number if number == i * i { print("The squared \(number) is \(i)") return } } print("\(number) is not a perfect square between 1 and 10_000") default: print("You are out of the loop") } } squareRootThisNumber(10000)`````` 1 Apr 23 are there reasons why should I not use this code 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 `0` indicates no root found and `-1` indicates an out of bounds condition), but that's ugly and you would have to document what those values mean and then remember them at the call site. Throwing an error is a much better solution. And just because a function throws, you don't necessarily have to use a `do ... catch` block to handle it. You can use `try?` to turn your result into an `Optional` (say, as part of an `if let` or `guard let` test), or `try!` to force unwrap your result (which I wouldn't recommend in this case). Or, you could wrap the result in a `Result` data type, if you were so inclined. 1 May 8 Could someone check my code, please? ``````enum SqrtError: Error { case range, absence } func squareRoot(_ n: Int) throws -> Int { if n < 1 || n > 10000 { throw SqrtError.range } var temp = 1 while temp * temp <= n { if temp * temp == n { return temp } temp += 1 } throw SqrtError.absence } for i in 0...10001 { do { var n = try squareRoot(i) print("Square root of \(i) is \(n)") } catch SqrtError.range { print("out of bounds") } catch SqrtError.absence { print("no root") } } `````` May 8 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? ``````var temp = 1 while temp * temp <= n { if temp * temp == n { return temp } temp += 1 }`````` 2 May 9 @Obelix I have no idea( Could you please suggest? May 9 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. ``````// ๐๐ผ (1) Set Starting Value var temp = 1 // ๐๐ผ (2) Test end condition while temp * temp <= n { print(temp) if temp * temp == n { return temp } // ๐๐ผ (3) Increment counter temp += 1 }`````` A more Swifty way would use a `for-loop` structure. This combines the three steps in your code into a single line of code. (I pulled the code out of the throwing function just to demonstrate the loop. Run this in Playgrounds.) ``````// What number do you want to find the square root of? var potentialSquare = 1000 // Combine start and end into a range. // Swift automatically increments for you // ๐๐ผ Auto increment ๐๐ผ This is a range. for potentialSquareRoot in 1.. potentialSquare { // throw SquareRootError.noSquareRoot print("No square root for \(potentialSquare)."); break } }``````

SAVE 50% To celebrate WWDC24, all our books and bundles are half price, 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.

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

You are not logged in