Swift
[Swift] Conditional Statements (조건문)
learner._.Kio
2021. 2. 16. 15:40
목차
- if Statement (if문)
- if
- else
- else-if
- switch Statements
- switch case
- switch case where
- guard Statements
if Statement (if문)
- if
- else
- else-if
If
if condition {
statements
}
let id = "patrick"
let password = "1234"
if id == "patrick" {
print("valid id") // vaild id
}
if password == "1234" {
print("vaile password") // vaild password
}
else
if condition {
statements
} else {
statements
}
if id == "patrick" && password == "1234" {
print("login succese") // login succese
} else {
print("login fail") // login fail
}
else if
if condition {
statements
} else if condition {
statements
} else {
statements
}
let score = 85
if score >= 90 {
print("A")
} else if score >= 80 {
print("B") // score가 85점이므로 "B"가 출력
} else {
print("Out")
}
// 가장 까다로운 조건을 먼저 처리하고 가장 느슨한 조건은 나중에 처리해야한다.
switch Statements
-
switch case
-
switch case where
-
Interval Matching (범위 매칭)
-
Fall Through
switch case
switch valueExpression {
case pattern:
statements
case pattern, pattern:
statements
default:
statements
}
let num = 1
switch num {
case 1: // num이 1일 때 실행
print("num = 1")
case 2, 3: // num이 2 or 3일 때 실행
print("num = 2 or 3")
default: // num이 그 외 값일 때 실행
print("others")
}
// switch는 모든 경우의 수를 써야한다.
// 각 경우에 최소 1줄 이상의 코드가 필요하다.
switch case where
switch valueExpression {
case pattern where condition: // pattern이 일치하고 condition도 일치해야 실행된다.
statements
default:
statements
}
let salary = 150
let intern = "인턴"
switch intern {
case intern where salary <= 150: // intern || salary <= 150 충족
print("노예입니다.") // 노예입니다.
default:
print("others")
}
Interval Matching (범위 매칭)
let temperature = -8
switch temperature {
case ..<10:
print("Cold")
case 11...20:
print("Cool")
case 21...27:
print("Warm")
case 28... :
print("Hot")
default:
break
}
Fall Through
let num = 1
switch num {
case 1: // num이 1일 때 실행
print("num = 1") // "num = 1" 출력 후 switch 구문 종료
case 2, 3:
print("num = 2 or 3")
default:
break
}
switch num {
case 1: // num이 1일 때 실행
print("num = 1") // "num = 1" 출력 후 switch 구문 종료
fallthrough // 이어지는 block 실행
case 2, 3: // case 검사
print("num = 2 or 3")
default:
break
}
guard Statement
guard
- guard 특징
- guard문에서는 else 필수이고, 반드시 코드의 진행을 중지시켜야한다.
- if 문에 비해 코드가 깔끔해진다.
- 대부분 Local Scope에서 사용한다.
- optinalBinding과도 사용할 수 있다.
- guard 선언
guard condition else { // guard문에서는 else 필수
statements // condition = false 일때, else 부분 실행
}
guard optionalBinding else { // optinalBinding과도 사용할 수 있다.
statements
}
- 예시
func validate(id: String?) -> Bool {
guard let id = id else {
return false
}
guard id.count >= 5 else {
return false
}
return true
}
validate(id:"12345") // true