[Swift] Control Flow

김승윤·2022년 4월 27일

Swift 정리

목록 보기
4/6
post-thumbnail

Control Flow (제어문)

Swift 에서는 while loop, if guard, switch, for-in 문 등 많은 제어문을 제공한다.

For-In Loops

for-in loops는 배열, 숫자, 문자열을 순서대로 순회(iterate)하기 위해 사용한다.

튜플을 순회하며 제어할 수도 있다.

let numberOfLegs = ["spider": 8, "ant": 6, "cat": 4]
for (animalName, legCount) in numberOfLegs {
    print("\(animalName)s have \(legCount) legs")
}
// ants have 6 legs
// spiders have 8 legs
// cats have 4 legs

사전에 담긴 콘텐츠는 정렬이 되지 않은 상태이기 때문에 사전에 넣었떤 순서대로 순회되지 않는다.

숫자 범위를 지정해 순회할 수 있다.

for index in 1...5 {
	print("hi")
}

순서가 상관없다면 변수자리에 _ 를 사용해 성능을 높이자.

for _ in 1 ... 10 {
	print("hi")
}

범위 연산자와 함께 사용가능하다.

for tickMark in 0..<minutes {

}

stride(from:to:by:) 함수와 함께 사용가능하다.

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

While Loops

Swift에서는 while과 repeat-while 를 지원한다.

  • While

    조건이 거짓일때까지 구문을 반복한다.
while condition {
	statements
}
  • Repeat-While

    구문을 최소 한 번 이상 실행하고 while 조건이 거짓일때까지 반복한다.
    do while 과 유사하다.
repeat {
	statements
} while condition

Conditional Statements

Swift에서는 if 와 switch 두 가지의 조건 구문을 제공한다.

  • If

temperatureInFahrenheit = 90
if temperatureInFahrenheit <= 32 {
    print("It's very cold. Consider wearing a scarf.")
} else if temperatureInFahrenheit >= 86 {
    print("It's really warm. Don't forget to wear sunscreen.")
} else {
    print("It's not that cold. Wear a t-shirt.")
}
// Prints "It's really warm. Don't forget to wear sunscreen."
  • 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")
}
// Prints "The last letter of the alphabet"

Swift 에서는 break 를 적지 않아도 특정 case가 완료되면 자동으로 Switch 를 빠져 나오게 된다.

case 안에 최소 하나의 실행 구문이 반드시 있어야 한다.

복수의 case 조건을 혼합할 수 있다.

case "a", "A":
    print("The letter A")

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

case 1..<5:
    naturalCount = "a few"

튜플을 조건으로 사용할 수 있다.

case (0, 0):
    print("\(somePoint) is at the origin")
  • 값 바인딩

    특정 x,y 값을 각각 다른 case에 정의하고 그 정의된 상수를 또 다른 case에서 사용할 수 있다.
case let (x, y):
    print("somewhere else at (\(x), \(y))")
}
  • Where

    case 에 where 조건을 사용할 수 있다.
case let (x, y) where x == y:

Control Transfer Statements (제어 전송 구문)

코드를 계속 진행할지 말지를 결정하거나 실행되는 코드의 흐름을 바꾸기 위해서 사용한다.
continue, break, fallthrough, return, throw

  • Continue

    현재 loop를 중지하고 다음 loop을 수행하도록 한다.

  • Break

    전체 제어문의 실행을 즉각 중지시킨다.

  • fallthrough

    이후의 case에 대해서도 실행하게 한다.
    case 조건을 확인하지 않고 그냥 다음 case 를 실행하게 만든다.

  • Labeled Statements

label name: while condition {
    statements
}
  • Early Exit

    guard 를 이용해 특정 조건을 만족하지 않으면 이 후 코드를 실행하지 않도록 방어코드를 작성할 수 있다.

Checking API Availability

Swift에서는 기본으로 특정 플랫폼과 특정 버전을 확인하는 구문을 제공해준다.

if #available(platform name, version ..., *) {
    statements to execute if the APIs are available
} else {
    fallback statements to execute if the APIs are unavailable
}
profile
정리왕을 꿈꾸며!

0개의 댓글