Ternary operator는 <if...else> 구문 대신 사용될 수 있는 연산자이다.
3개의 피연산자를 취하므로 3항 연산자(Ternary Conditional Operator)라고 부른다.
문법
condition ? expression1 : expression2
의미:
if condition is true, expression1 is executed.
if condition is false, expression2 is executed.
예제 1
2로 나눈 나머지가 0이면 "Even", 아니면 "Odd"를 반환하는 함수
func solution(_ num:Int) -> String {
return num % 2 == 0 ? "Even" : "Odd"
}
예제 2
40점 이상이면 "pass", 아니면 "fail"
// program to check pass or fail
let marks = 60
// use of ternary operator
let result = (marks >= 40) ? "pass" : "fail"
print("You " + result + " the exam")
(출처: https://www.programiz.com/swift-programming/ternary-conditional-operator)
예제 3
각에서 0도 초과 90도 미만은 예각, 90도는 직각, 90도 초과 180도 미만은 둔각 180도는 평각으로 분류합니다.
각 angle이 매개변수로 주어질 때 예각일 때 1, 직각일 때 2, 둔각일 때 3, 평각일 때 4를 return하도록 solution 함수를 완성해주세요.
import Foundation
func solution(_ angle: Int) -> Int {
guard angle > 0 && angle <= 180 else {
print("'angle' must be an integer greater than 0 and less than or equal to 180.")
return 9
}
return (angle < 90) ? 1 :
(angle == 90) ? 2 :
(angle < 180) ? 3 : 4
}
문제 출처: 프로그래머스 (링크)
'Swift > 문법' 카테고리의 다른 글
[Swift] Character를 Int로 변환하기 - .wholeNumberValue, hexDigitValue, Int(String(문자)) (0) | 2024.02.07 |
---|---|
[Swift] 고차함수 - map, filter, reduce (2) | 2024.02.07 |
[Swift] 함수 - 매개변수 앞 언더바('_') (외부 매개변수, 내부 매개변수) (2) | 2024.02.07 |
앱개발 용어 정리(3) - 구조체와 클래스, 메서드 (0) | 2024.02.07 |
앱개발 용어 정리(2) - 자료형, 변수와 상수 (0) | 2024.02.07 |