100days of SwiftUi Day08 && check Point04

44 阅读1分钟

at first I want to tell the problem of checkpoint 04

The challenge is this. write a function that accepts an integer from 1 through 10000 and return the integer square root of that number. That sounds easy but there are some catches:

1 if the number is less than 1 or greater than 10000 you should throw an"out of bounds" error
2 you should only consider integer square roots don't worry about the square root of 3 being 1.732 for example.
3 if you can't find the square root, throw a " no root" error

The anwser is that

`import Foundation

func findSquareroot ( for myNumber:Int ) throws -> Int { //   guard 与 if差不多 不够if还有其他选择 而guard只有确定 判定为否时

    guard myNumber >= 1 && myNumber <= 10000 else     {         throw SquareRootError.outOfBounds     }     for i in 1...myNumber     {         if myNumber  == i*i         {

          return i         }     }     throw SquareRootErrors.noRoot } let myNumber = 101

do{     let result = try findSquareroot(for: myNumber)

     print("The square root of (myNumber) is (result)")

} catch SquareRootErrors.outOfBounds{

    print( "The nunber you provided isnot with in the accepted range") }catch SqaureRootErrors.noRoot {     print(" The number of your choice has no square root")

}`

and then we should talk How to deal with Error
such as How to Handle errors in functions

`do {

    try throwingFunction01()

    nonThrowingFunction1()

    try throwingFunction02()

    nonThrowingFunction2()

    try throwingFunction3()

    

}catch

{

    

}`