티스토리 뷰

1. Conditional Operator

 기본적으로 swift의 if 조건문은 아래와 같이 사용할 수 있다.

let condition = 0

if condition == 0 {
    print("condition is correct")
} else if condition < 0 {
    print("condition is less than zero")
} else {
    print("condition is bigger than zero")
}

삼항연산자 또한 사용이 가능하다.

let contentHeight = 40
let hasHeader = true
let rowHeight = contentHeight + (hasHeader ? 50 : 20)

2. Nil-Coalescing Operator

 Nil-Coalescing 연산자는 ?? 형태로 Optional 변수가 nil 값을 가지고 있는 지를 판단하여 nil 값이 아닌  value 를 가지고 있다면 해당   Optional변수를 unwrap하여 나타내며, 아닐 시 다른 값을 출력한다. 

 

기본적으로 아래의 역할을 수행한다고 생각하면 된다.

a != nil ? a! : b

이를 ?? 연산자를 사용하여 나타내면 아래와 같다.

let defaultColorName = "red"
var userDefinedColorName: String?   // defaults to nil

var colorNameToUse = userDefinedColorName ?? defaultColorName

3. Range Operators(For - In)

 swift 에서 for 문을 사용하려면 기본적으로 범위 연산자를 사용하여 for in 구문으로 처리하는 거 같다.

 

- Closed Range Opertor:

 닫힌 범위 내에서 반복문을 실행할 때 사용하며 아래와 같이 시작과 끝을 정하여 사용한다.

for index in 1...5 {
    print("\(index)")
}
// 출력 //
// 1
// 2
// 3
// 4
// 5

 

- Half-Open Range Operator:

 a..<b 의 형태로 a 부터 b 보다 작을 때까지의 범위를 가지며, 보통 배열의 크기를 사용하여 반복문을 돌릴 때 많이 사용한다.

let names = ["Anna", "Alex", "Brian", "Jack"]
let count = names.count
for i in 0..<count {
    print("Person \(i + 1) is called \(names[i])")
}
// Person 1 is called Anna
// Person 2 is called Alex
// Person 3 is called Brian
// Person 4 is called Jack

 

- One-Sided Ranges:

닫힌 범위와는 다르게 한쪽 기준점부터 인덱스가 끝날 때까지 반복문을 돌도록 지정해야 할 때는 아래와 같은 One-sided 연산자를 사용한다.

let names = ["Anna", "Alex", "Brian", "Jack"]

for name in names[2...] {
    print(name)
}
// Brian
// Jack

for name in names[...2] {
    print(name)
}
// Anna
// Alex
// Brian

for name in names[..<2] {
	print(name)
}
// Anna
// Alex

 

또한 for - in 문을 순서대로 제어할 필요가 없다면, 변수 자리에 _ 키워드를 사용하면 성능을 더욱 높일 수 있다.

let base = 3
let power = 10
var answer = 1

for _ in 1 ... power {
    answer *= base
}

print("\(base) to the power of \(power) is \(answer)")

 

stride(from: to: by:) 함수와 함께 사용할 수 있으며, 아래 예제는 구간을 5로 설정한 예시이다.

let minutes = 60
let minuteInterval = 5

for tickMark in stride(from: 0, to: minutes, by: minuteInterval) {
    print("\(tickMark)")
}

4. While Loops

Java 의 while 과 do-while 과 동일하게 swift 는 while문과 repeat-while문을 지원한다.

 

while문의 문법적 형태는 아래와 같다.

while condition {
    statements
}

repeat-while 문은 do-while과 동일하게 repeat 아래 구문을 작성하고 최소 한번 이상 실행한 뒤 while 조건이 false 가 될 때까지 반복한다.

repeat {
    statements
} while condition

5. Switch

switch 문의 기본적인 형태는 아래와 같다. 

let someCharacter: Character = "z"

switch someCharacter {
case "a":
    print("The first letter of the alphabet")
case "z":
    print("The last letter of the alphabet")
default:
    print("Some other character")
}

한가지 특징은 swift의 switch구문이 default를 만날 때 까지 암시적 진행을 하지 않기 때문에 굳이 break를 추가하지 않아도 조건에 맞는 구문만 실행한다는 점이다.

 

아래와 같이 콤마로 구분하여 복수의 case 조건을 혼합하여 사용할 수도 있다.

let anotherCharacter: Character = "a"
switch anotherCharacter {
case "a", "A":
    print("The letter A")
default:
    print("Not the letter A")
}

 

숫자의 특정 범위을 조건으로 사용할 수도 있다.

let approximateCount = 62
let countedThings = "moons orbiting Saturn"
let naturalCount: String
switch approximateCount {
case 0:
    naturalCount = "no"
case 1..<5:
    naturalCount = "a few"
case 5..<12:
    naturalCount = "several"
case 12..<100:
    naturalCount = "dozens of"
case 100..<1000:
    naturalCount = "hundreds of"
default:
    naturalCount = "many"
}
print("There are \(naturalCount) \(countedThings).")

 

또한 튜플로도 switch 구문을 사용할 수 있다.

let somePoint = (1, 1)
switch somePoint {
case (0, 0):
    print("\(somePoint) is at the origin")
case (_, 0):
    print("\(somePoint) is on the x-axis")
case (0, _):
    print("\(somePoint) is on the y-axis")
case (-2...2, -2...2):
    print("\(somePoint) is inside the box")
default:
    print("\(somePoint) is outside of the box")
}

 

튜플을 조건으로 사용할 때는 아래와 같이 값 바인딩을 하여 상수를 하나 정의한 뒤, case 구문 내에서 사용할 수도 있다.

let anotherPoint = (2, 0)
switch anotherPoint {
case (let x, 0):
    print("on the x-axis with an x value of \(x)")
case (0, let y):
    print("on the y-axis with a y value of \(y)")
case let (x, y):
    print("somewhere else at (\(x), \(y))")
}

또한 이 때, where문을 사용하여 튜플의 모든 인자를 상수로 사용할 수도 있다.

let yetAnotherPoint = (1, -1)
switch yetAnotherPoint {
case let (x, y) where x == y:
    print("(\(x), \(y)) is on the line x == y")
case let (x, y) where x == -y:
    print("(\(x), \(y)) is on the line x == -y")
case let (x, y):
    print("(\(x), \(y)) is just some arbitrary point")
}

 

Comments