[Swift] #3 - 흐름 제어
2021. 8. 27. 14:59ㆍiOS Development/Swift
** if 조건문
- 코드 블럭: {}, 실행 단위이며 영향력을 미치는 범위를 나타냄
// if else 조건문
let adult = 19
let age = 15
if age < adult {
print("당신은 미성년자")
} else {
print("당신은 성인")
}
// 중첩 if 문
let gender = "female"
if age < adult {
if gender == "female" {
print("당신은 미성년 여성")
} else {
print("당신은 미성년 남성")
}
}
** Switch 조건문
- 각 case를 코드블럭으로 구분하지 않음
- case 마다 break문을 작성하지 않아도 됨
// switch 조건문 : 다중 선택
let browser = "Chrome"
var browserName = ""
switch browser {
case "IE": browserName = "인터넷 익스플로러"
case "FF": browserName = "파이어 폭스"
case "Chrome": browserName = "크롬"
case "Opera": browserName = "오페라"
case "Safari": browserName = "사파리"
default : browserName = "알려지지 않은 브라우저"
}
print("브라우저명은 \(browserName)")
var testAge = 17
switch testAge {
case 1, 2, 3: print("Baby")
case 4..<20: print("Child")
default : print("Adult")
}
** for 반복문
- 내부에서 사용 가능항 변수를 자동적으로 생성
- 딕셔너리를 출력할 때 랜덤하게 출력됨 -> 딕셔너리 자체는 순서가 없기 때문에
// for in 구문
for row in 1...5 {
print("2 * \(row) = \(2 * row)")
}
for _ in 1..<5 { // 루프 상수의 생략
print("Loop")
}
// 활용: 구구단 출력
for i in 1...9 {
for j in 1...9 {
print("\(i) X \(j) = \(i * j)")
}
print()
}
// 활용: Collections 출력
let bts = ["진", "슈가", "제이홉", "RM", "지민", "V", "정국"]
for name in bts {
print("Hello, \(name)")
}
var capitals = ["KR":"Seoul", "EN":"London", "FR":"Paris"]
for ((country, capital)) in capitals {
print("\(country)'s capital = \(capital)")
}
** while 반복문
- 탈출 조건이 필수
// while 구문
var testWhileAge = 0
while testWhileAge < 5 {
print("\(testWhileAge)살: 아직 5살 미만")
testWhileAge += 1
}
print("이제 5살 !")
// repeat ~ while 구문
var n = 100
repeat {
n *= 2
print("\(n)")
} while n < 1000
** break, continue
- break: 해당 loop를 바로 탈출
- continue: 아래의 명령어들을 수행하지 않고 다음 loop로 넘어감
// break, continue
for row in 0...5 {
if row == 2 {
break
}
print("\(row) was executed !")
}
for row in 0...5 {
if row == 2 {
continue
}
print("\(row) was executed !")
}
** 홀수 출력하기
// 홀수 출력
for num in 0...10 {
if num % 2 == 0 { // 쨕수이면 pass
continue
}
print(num)
}
'iOS Development > Swift' 카테고리의 다른 글
[Swift] #5 - 함수 (0) | 2021.09.01 |
---|---|
[Swift] #4 - Collections (0) | 2021.08.30 |
[Swift] #2 - 연산자 (0) | 2021.08.26 |
[Swift] #1 - 상수와 변수 (0) | 2021.08.26 |
[Swift] #0 - iOS 및 Swift 개요 (0) | 2021.08.26 |