iosswiftfunctionsqrt

Why is this handmade square root function in Swift not returning the value, but throws the error?


Just trying to create an analog of sqrt() in Swift, but it throws .noRoot in all the matched cases. Also I add the error .outOfBound, this is working correctly.

import UIKit

enum WrongNumber: Error {
  case outOfBounds
  case noRoot
}

func mySqrt(_ number: Int) throws -> Int {
  if number < 1 || number > 10_000 {
    throw WrongNumber.outOfBounds
  }
  
  var result = 0
    for i in 1...10_000 {
      if i * i == number {
        result = i
      } else {
        throw WrongNumber.noRoot
      }
   } 
  return result
}

var number = 1000

do {
  let result = try mySqrt(number)
    print(result)
}
catch WrongNumber.outOfBounds {
    print("You're puting a wrong number. Please try again with range from 1 to 10_000")
 }
catch WrongNumber.noRoot {
    print("There is no square root in your number")
}

Solution

  • You should return once you find it

    func mySqrt(_ number: Int) throws -> Int {
      if number < 1 || number > 10_000 {
        throw WrongNumber.outOfBounds
      }
      for i in 1...10_000 {
        if i * i == number {
          return i
        }
      } 
      throw WrongNumber.noRoot
    }