[Swift] Conditional Statements
※ if Statements
if condition {
code
}
if condition {
statements
} else {
statements
}
여기서 condition 은 Bool 값이다. (true, false)
- if
var temperatureInFaherenheit = 30
if temperatureInFaherenheit <= 32 {
print("It's very cold. Consider wearing a scarf.")
}
- if - else
temperatureInFaherenheit = 90
if temperatureInFahereheit <= 32 {
print("It's very cold. Consider Wearing a sarf.")
}else {
print("It's not that cold. Wear a t-shirt")
}
- if - else if - else
temperatureInFaherenheit = 90
if temperatureInFahereheit <= 32 {
print("It's very cold. Consider Wearing a scarf.")
} else if temperatureInFahereheit >= 86 {
print("It's really warm. Don't forget to wear sunscreen.")
} else {
print("It's not that cold. Wear a t-shirt")
}
- if - else if
temperatureInFaherenheit = 72
if temperatureInFahereheit <= 32 {
print("It's very cold. Consider Wearing a scarf.")
} else if temperatureInFahereheit >= 86 {
print("It's really warm. Don't forget to wear sunscreen.")
}
- Logical And Operator
아래 두 if문은 동일하다.
if (temperatureInFahrenheit > 0) && (temperatureInFahrenheit % 2 == 0) {
}
if temperatureInFahrenheit > 0, temperatureInFahrenheit % 2 ==0 {
}
※ switch Statements
switch value {
case value 1:
respond to value 1
case value 2,
value 3:
respond to value 2 or 3
default:
otherwise, do something else
}
switch 문은 가능한 모든 사례를 반드시 다루어야 한다.
- Interval Matching
let approximateCount = 30
switch approximateCount {
case 0...50:
print("0 ~ 50")
case 51...100:
print("51 ~ 100")
default:
print("Something else")
}
- Compound cases
let someCharacter: Character = "e"
switch someCharacter {
case "a", "e", "i", "o", "u":
print("\(someCharacter) is a vowel")
case "b", "c", "d", "f", "g", "h", "j", "k", "l", "m", "n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z":
print("\(someCharacter) is a consonant")
default:
print("\(someCharacter) is not a vowel or a consonant")
}
※ Early Exit
- guard Statements
func update(age: Int) {
guard 0...100 ~= age else { return }
print("Pass")
}
update(age: 2)
update(age: -1)
update(age: 100)
'iOS > Swift' 카테고리의 다른 글
[Swift] Tuples (0) | 2018.05.23 |
---|---|
[Swift] Loops (0) | 2018.05.23 |
[Swift] Function (0) | 2018.05.18 |
[Swift] Basic Operators (0) | 2018.05.17 |
[Swift] 기본 문법 (0) | 2018.05.14 |