Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You should return once you find it

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 {
        return i
      }
   } 
  throw WrongNumber.noRoot
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading