swift.org를 참고하여 정리한 글입니다.
Swift.org
Swift is a general-purpose programming language built using a modern approach to safety, performance, and software design patterns.
www.swift.org
조건과 반복문에 대해서 알아보자.
if & else
let int3 = 3
if 5 > int3 {
print("OK")
}
// if와 else
if 5 > int3 {
print("OK")
} else {
print("NO")
}
// else-if로 조건을 쓸 수 있다.
if 2 > int3 {
print("if 2")
} else if 5 > int3{
print("else if 2")
}
switch-case
let switchValue = 0
switch switchValue {
case ..<4 :
print("switch case ..<4")
fallthrough // 사용하면 조건과 상관없이 다음 case가 실행됩니다.
case 1,3,5,7,9 :
print("switch case 1,3,5,7,9")
case 5... :
print("switch case 5...")
case 0,2,4,6,8 :
print("switch case 0,2,4,6,8")
default:
print("switch default")
}
// switch case ..<4
// switch case 1,3,5,7,9
삼항연산자
// condition ? {true condition code} : {false condition code}
let int51 = 51
(100 > int51) ? print("100보다 작아요.") : print("100보다 같거나 커요.")
// "100보다 작아요."
for-in
for num in 0...4 {
print(num)
}
// 0
// 1
// 2
// 3
// 4
let anyDictionary: [String: Any] = [ "dictionary" : [4:"four"],
"array": [1,2,3,4,5],
"int": 5 ]
for element in anyDictionary {
print(element)
}
// (key: "dictionary", value: [4: "four"])
// (key: "array", value: [1, 2, 3, 4, 5])
// (key: "int", value: 5)
while
var num = 3
// 조건 체크 -> 실행 -> 조건체크 ...
while num > 0 {
print("while num: \(num)")
num -= 1
}
// while num: 3
// while num: 2
// while num: 1
repeat-while
// 실행 -> 조건체크 -> 실행 ...
num = 0
repeat {
print("repeat-while num: \(num)")
num -= 1
} while num > 0
// repeat-while num: 0
break
for-in, while, repeat-while의 반복 루프 중 break를 통해 반복을 멈추고 코드블럭을 빠져나올 수 있다.
num = 1
while num > 0 {
print("while num: \(num)")
num += 1
if num == 3 {
print("break! \(num)")
break
}
}
// while num: 1
// while num: 2
// break! 3
'iOS > Swift' 카테고리의 다른 글
[Swift] Optional(옵셔널) (0) | 2022.06.09 |
---|---|
[Swift] Function (0) | 2022.06.09 |
[Swift] Collection Type (0) | 2022.06.04 |
[Swift] 기본 데이터 타입 (0) | 2022.06.04 |
[Swift] Protocol (0) | 2022.05.27 |