Dev/Swift

Swift: 제어문(control flow)

두넌 2023. 5. 14.

DAY 07

제어문(control-flow)

 

For


// swift3 이후 없어진 문법
for var i = 0; i<10; i+=1 {
    print(i)
}
// 다음과 같이 수정해야 함
for i in 0..<10 {
    print(i)
}

 

For-in 반복문


for-in 반복문은 컬렉션 또는 숫자 범위 내에 있는 목록을 반복

for 상수명 in 컬렉션 또는 범위 {
    // code
}

다음과 같이 _ 로 참조체(i) 생략할 수 있다

for _ in 1...5 {
    print("Hello")
}

 

배열의 항목을 접근하는 방법

let names = ["Anna", "Alex", "Brian", "Jack"]
for name in names {
    print(name)
}

 

dictionary의 항목 접근

let numberOfLegs = ["spider": 8, "ant": 6, "cat": 4]

for (animalName, legCount) in numberOfLegs {
    print("\(animalName)s have \(legCount) legs")
}
spiders have 8 legs
ants have 6 legs
cats have 4 legs

 

repeat-while 반복문


repeat {
    ///
} whlie (조건식)

do-while이 아닌 repeat-while로 사용한다

 

if 문


for i in 1..<10 {
    if i > 5 { break }
    print(i)
}

2번 라인

다른 프로그래밍 언어들과는 다르게, 스위프트에서는 if문 다음의 실행 코드가 한 줄이라도 괄호({})를 필수적으로 사용해야 함

if문 조건에서 콤마의 의미

if a < b && d > c {
    print("true")
}

if a < b, d > c {
    print("true")
}

동일한 코드이다

스위프트에서 콤마의 의미는 논리적인 AND연산의 의미와 같다

 

guard 문


guard문은 표현식이 거짓(false)로 판달될 경우에 수행될 else 절을 반드시 포함해야 함

  • else 절에 속한 코드는 현재의 코드 흐름을 빠져 나갈 수 있는 구문(return, break, continue, throw 구문)을 반드시 포함해야 함
  • 또 다른 함수를 else 코드 블록 안에서 호출할 수도 있음
guard <boolean 표현식> else {
    // 표현식이 거짓일 경우에 실행될 코드
    <코드 블록을 빠져 나갈 구문>
}
// 표현식이 참일 경우에 실행되는 코드

guard문은 기본적으로 특정 조건에 맞지 않을 경우에 현재의 함수나 반복문에서 빠져 나갈 수 있도록 하는 '조기 출구(early exit)' 전략을 제공

 

func multiplyByTen(value: Int?) {
    guard let number = value, number < 10 else {
        print("10보다 큼")
        return
    }
    print(number * 10)
}

multiplyByTen(value: 3)

값을 unwrap하기 위하여 옵셔널 바인딩 하고, 그 값이 10보다 작은지 검사

  • 변수를 언래핑할 수 없거나 값이 10보다 크면, else절이 실행되어 에러 메시지 출력 후 return
  • 언래핑된 number변수를 guard문 밖에 있는 코드가 사용할 수 있음 (if문을 이용할 시 못함)

 

if let vs guard let


func printName(firstName: String, lastName: String?) {
    if let lName = lastName {
        print(lName, firstName)
    } else {
        print("성이 없음")
    }

    guard let lName = lastName else {
        print("성이 없음")
        return
    }
    print(lName, firstName)
}

printName(firstName: "길동", lastName: "홍")

 

switch-case문


switch 표현식 {
    case match1:
        구문
    case match2:
        구문
    case match3, match4:
        구문
    default:
        구문
}

각 case문 마지막에 break가 자동으로 들어있음

case에는 최소 한가지 이상의 실행문이 들어있어야 함

comma(,)를 이용하여 실행될 공통 코드로 그룹 case문을 만들 수 있음

 

switch-case문에서의 범위 지정 매칭


let num = 25
let count: String
switch num {
    case 0...9:
        count = "한자리 수"
    case 0...99:
        count = "두자리 수"
    case 100...999:
        count = "세자리 수"
    default:
        count = "네자리 수 이상"
}

print("\(count)입니다.")

 

switch-case에서 where절 사용하기


where절을 switch case에 부가적인 조건을 추가하기 위하여 사용함

var temperature = 60
switch (temperature) {
    case 0...49 where temperature % 2 == 0:
        print("Cold and even")
    case 50...79 where temperature % 2 == 0:
        print("Warm and even")
    case 80...110 where temperature % 2 == 0:
        print("Hot and even")
    default:
        print("Temperature out of range or odd")
}

if문에서는 comma(,)를 통하여 부가적인 조건을 추가(논리적인 AND) 하고, switch, catch, while, guard, for 등에서는 where을 사용하여 부가적인 조건을 추가함

 

fallthrough


swift에서는 case문 다음에 break문을 포함할 필요가 없음

일치하는 case문을 만나면 자동으로 빠져나옴

case별로 빠져나가지 않고 아래로 계속 내려가게 하려면 fallthrough문 사용

var value = 4
switch (value) {
    case 4:
        print("4")
        fallthrough
    case 5:
        print("5")
        fallthrough
    case 6:
        print("6")
        fallthrough
    default:
        print("7")
}

// 4 5 6 7

댓글