100 days of swiftui: checkpoint 4
https://www.hackingwithswift.com/quick-start/beginners/checkpoint-4
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:
As a reminder, if you have number X, the square root of X will be another number that, when multiplied by itself, gives X. So, the square root of 9 is 3, because 3x3 is 9, and the square root of 25 is 5, because 5x5 is 25.
enum CalculateError: Error {
case outOfBound, notInteger
}
func findSqrt(num: Int) throws -> Int {
if num > 10000 || num < 1 {
throw CalculateError.outOfBound
} else {
for i in 1...100 {
if i * i == num {
return i
}
}
throw CalculateError.notInteger
}
}
let num = 3
do {
let result = try findSqrt(num: num)
print("\(result) is the square root of \(num)!")
} catch CalculateError.outOfBound {
print("The number is out of bound!")
} catch CalculateError.notInteger {
print("The result is not an integer!")
} catch {
print("no root")
}
1부터 10,000까지 중 한 숫자의 루트를 찾는 것이기에, 루트를 찾을 때 반복문으로 1(1의 루트)부터 100(10,000의 루트)까지만 확인한다. 그리고 이외에 숫자가 설정한 범위를 벗어나거나 루트 값이 정수가 아니면 에러를 발생하도록 설정했다.
코드 파일
https://github.com/soaringwave/Ios-studying/blob/main/findSqrt.playground/Contents.swift