@kib asks about function return values:
return input //what do I need to return here
Welcome to HackingWithSwift
This is a great place to start your Swift learning journey. There are many great lessons ahead and this forum has plenty of folks who like to help either by simply giving you the direct answer, by giving hints to help you learn, and all combinations inbetween.
The Direct Answer
When you define a function that throws or returns a value, the Swift interpreter holds you firmly to that contract. So while you believe you covered all the if
and else
cases, it seems the compiler disagrees. To find out why, be the compiler.
// ๐๐ผ Check all values 1 through 100
for i in 1...100 {
if(i*i==input)
{
// ๐๐ผ You found the root value
return i
}
else if(i*i>input)
{
// ๐๐ผ You prove i * i is greater than input value
throw SqrtError.noRoot
}
}
// If you're here, what happened?
// But what is returned if neither of these cases is true?
Is there a case where i * i
is not equal to the input
value AND i * i
is NOT greater than the input
value?
Your mental math may say this will never happen, but the compiler insists you explicitly state this in code!
But rather than returning a nonsense number, such as -3, this is a great place to extend your SqrtError
codes.
// Consider adding another error code
enum SqrtError: Error {
// ๐๐ผ This code will help you debug logic errors in future revisions
case outOfBounds, noRoot, logicError}
//. ........ snip .........
// ๐๐ผ Check all values 1 through 100
for i in 1...100 {
// ๐๐ผ You found the root value
if(i*i==input) { return i }
// ๐๐ผ You prove i * i is greater than input value
else if(i*i>input) { throw SqrtError.noRoot }
}
// If you're here, what happened?
// ๐๐ผ Your code encountered a logic error!
throw SqrtError.logicError
Keep Coding