QA Automation/swift5
6. 흐름제어
kokorii_
2023. 6. 20. 22:59
6.1 조건문
6.1.1 if 구문
스위프트의 if 구문은 조건의 값이 꼭 Bool 타입이어야 한다
- 마지막 else는 생략 가능
- if 단독 사용 가능
if first > second {
print("test")
} else if first < second {
print("test2")
} else {
print("test3")
}
var isDarkMode : Bool = false
if isDarkMode {
print("dark mode")
} else {
print("it's not dark mode")
}
6.1.2 Switch 구문
- break 키워드를 생략할 수 있음
- switch 구문의 case를 연속 실행하려면 fallthrough 키워드 사용
- case에 들어갈 비교값은 입력값과 데이터 타입이 같아야 한다
- 입력값으로 튜플도 사용할 수 있다
- default를 반드시 작성해야 한다
- case에 범위 연산자를 사용할 수 있으며, where 절을 사용하여 조건을 확장할 수 있다.
- 열거형과 같이 한정된 범위의 값을 입력으로 받을 때는 default를 생략할 수 있지만 전체 값에 대응하는 case를 구현하지 않는다면 default는 필수
- unknown : case의 확장을 염두한 대응, 가장 마지막 case로 작성해야 함
let vegetable = "red pepper"
switch vegetable {
case "celery":
print("Add some raisins and make ants on a log.")
case "cucumber", "watercress":
print("That would make a good tea sandwich.")
case let x where x.hasSuffix("pepper"):
print("Is it a spicy \(x)?")
default:
print("Everything tastes good in soup.")
}
// Prints "Is it a spicy red pepper?"
case _: //case default와 같은 표현
6.2 반복문
6.2.1 for문
- 기본 사용
for i in 0...2 {
print(i)
}
let hello: String = " Hello Swift! "
for char in hello {
print(char)
}
var result = 1
for _ in 1...3 {
result *=10
}
for i in 0...5 {
if i.isMultiple(of: 2) {
print(i)
continue
}
}
- 기본 컬렉션 타입과 사용
let friends: [String: Int] = ["jay":35, "blair":30]
for tuple in friends {
print(tuple)
}
for (key, value) in friends {
print("\\(key), \\(value)")
}
- 배열 반복
let trees = ["Pine","Oak", "Yew", "Maple", "Birch", "Myrtle"]
for tree in trees {
print(Tree)
}
- 기타
var myArray : [Int] = [0,1,2,3,4,5,6,7,8,9,10]
for item in myArray {
print("item: \\(item)")
}
var myArray : [Int] = [0,1,2,3,4,5,6,7,8,9,10]
for item in myArray where item > 5{
print("item: \\(item)")
}
6.2.2 while 문
- 특정조건이 성립하는 내부 코드 반복 실행
var names: [String] = ["joker", "jenny"]
while names.isEmpty == false {
print("goodbye, \\(names.removeFirst())")
}
6.2.3 repeat-while 문
- 다른 언어의 do-while문
- repeat 블록 1회 실행 후, wile 다음의 조건이 성립하면 반복 실행
var names: [String] = ["joker", "jenny"]
repeat {
print("goodbye, \\(names.removeFirst())")
} while names.isEmpty == false
6.3 구문 이름표
- break : 반복문을 빠져나오게 하는 키워드
- continue: continue를 만나면 해당 순서를 skip하고 다음 순번으로 넘어감
- 기타 등등 ..