importCocoaenumPasswordError:Error,LocalizedError{caseTooShortcaseObviousvarerrorDescription:String?{switchself{case.TooShort:returnNSLocalizedString("Password is too short",comment:"Too short")case.Obvious:returnNSLocalizedString("Password is too obvious",comment:"Obvious")}}}// although defined with `throws`,// this function doesn't have to throw an exceptionfunccheckPassword(_pwd:String)throws->Bool{ifpwd.count<6{throwPasswordError.TooShort}ifpwd=="123456"{throwPasswordError.Obvious}returntrue}do{letok=trycheckPassword("hello")print(ok)}catch{print("Error happened: \(error.localizedDescription)")}// ## Checkpoints/*
write a function that accepts an integer from 1 through 10,000, and returns the integer square root of that number. That sounds easy, but there are some catches:
You can’t use Swift’s built-in sqrt() function or similar – you need to find the square root yourself.
If the number is less than 1 or greater than 10,000 you should throw an “out of bounds” error.
You should only consider integer square roots – don’t worry about the square root of 3 being 1.732, for example.
If you can’t find the square root, throw a “no root” error.
*/enumRootError:Error,LocalizedError{caseoutOfBoundscasenoRootvarerrorDescription:String?{switchself{case.outOfBounds:returnNSLocalizedString("Out of Bounds",comment:"OOB")case.noRoot:returnNSLocalizedString("No root",comment:"NR")}}}funcsqroot(_num:Int)throws->Int{ifnum<1||num>10_000{throwRootError.outOfBounds}foriin1...100{ifi*i==num{returni}}throwRootError.noRoot}do{print(trysqroot(9))print(trysqroot(25))print(trysqroot(37))}catch{print("error happened: \(error.localizedDescription)")}
Top comments (0)
Subscribe
For further actions, you may consider blocking this person and/or reporting abuse
Top comments (0)