문제
- 문제 : 정수 num1, num2가 매개변수 주어집니다. num1과 num2를 곱한 값을 return 하도록 solution 함수를 완성해주세요.
- 제한사항
- 0 ≤ num1 ≤ 100
- 0 ≤ num2 ≤ 100
[방법 1] if문 사용
import Foundation
func solution(_ num1: Int, _ num2: Int) -> Int {
if num1 > 0 && num1 <= 100 && num2 > 0 && num2 <= 100 {
return num1 * num2
} else {
print("Error: 0 < num1 ≤ 100 and 0 < num2 ≤ 100")
return 0
}
}
[방법 2] guard문 사용
import Foundation
func solution(_ num1: Int, _ num2: Int) -> Int {
// Check if num1 is within the allowed range
guard num1 >= 0 && num1 <= 100 else {
print("Error: num1 should be between 0 and 100 inclusive.")
return 0
}
// Check if num2 is within the allowed range
guard num2 >= 0 && num2 <= 100 else {
print("Error: num2 should be between 0 and 100 inclusive.")
return 0
}
// If both num1 and num2 are within the allowed range, calculate the product
return num1 * num2
}
guard문 작성 방법
설명 : guard문은 조건이 만족되지 않을 경우, scope(함수, 메서드, 루프 등)을 exit하는 데에 사용된다.
코드 양식 :
guard condition else {
// [condition을 충족하지 않을 때 실행할 코드 작성]
// Usually includes transferring control using return, throw, break, continue, or fatalError()
}
// [condition을 충족할 때 실행할 코드 작성]
'Swift > Code Kata (알고리즘)' 카테고리의 다른 글
[Swift|코드카타] (프로그래머스) 입문 #10. 배열의 평균값 - reduce 함수 (0) | 2024.02.07 |
---|---|
[Swift|코드카타] (프로그래머스) 입문 #9. 짝수의 합 (for...in...where) (0) | 2024.02.07 |
[Swift|코드카타] (프로그래머스) 입문 #8. 각도기 (0) | 2024.02.07 |
[Swift|코드카타] (프로그래머스) 입문 #3. 나누기 (0) | 2024.02.07 |
[Swift|코드카타] (프로그래머스) 입문 #2. 두 수의 합 (0) | 2024.02.07 |