스피드 문법정리

5. Conditional Statements

Beginner Programmer 2020. 6. 11. 20:03

If Statement

If

조건을 평가한 후 그 값이 참이면 statements를 실행

if condition {
   statements
}

If else

if condition {
   statements
   } else {
     statements
   }

 

If else if

if condition {
   statements
} else if condition {
   statements
} else {
   statements
}

If 문장은 까다로운 문장에서 -> 느슨한 문장으로, 범위가 좁은 문장에서 -> 범위가 넓은 문장으로

Switch

값의 일치 여부에 따라서 실행할 코드를 결정, pattern이나 value 매칭에 자주 사용됨

switch valueExpression {
case pattern:
     statements
case pattern, pattern:
     statements
default:
     statements
}

where의 경우는 첫번째 case의 pattern 이 일치하고 조건을 모두 만족한다면 statements를 실행시킴

switch valueExpression {
case pattern where condition:
     statements
case pattern, pattern:
     statements
default:
     statements
}

Interval Matching

범위를 매칭 시키는 경우 사용

let temperature = -8

switch temperature {
case ..<10:
    print("Cold")
case 11...20:
    print("Cool")
case 21...27:
    print("Warm")
case 28...:
    print("Hot")
default:
    break

Fall through

switch 문장의 case의 일치 여부와 상관없이 나머지 문장을 무조건 실행

let num = 2

switch num {
case 1:
    print("One")
case 2:
    print("Two")
    fallthrough
case 3:
    print("Three")
default:
    break
    
 //  Two, Three

위의 예시에서 만약 fallthrough가 없었다면 Short-circuit Evaluaction (단락 평가)으로 case 2에서 switch 문이 종료되지만 fallthrough는 case일치 여부와 상관없이 나머지 문장을 모두 실행시킴

Value Binding Pattern

매칭시킬 대상을 상수나 변수로 바인딩한 후 case 블록에서 활용, where 절과 자주 같이 사용

case let name:
case var name:
let = a

switch a {
case var x where x > 100:
    x = 200
    print(x)
default:
    break
}

let pt = (1, 2)

switch pt {
case let (x, y):
    print(x, y)
case let (let x, let y):
    print(x, y)
case let (let x, var y):
    print(x, y)
case let (x, _):
    print(x)

Guard

Guard 문이 참이 된다면 다음 문장이 실행되고 만약 Guard문이 거짓이라면 else 문에서 종료됨, else 블록은 필수이며, 대부분 Local Scope에서 사용되고 else 블록은 해당 Local Scope를 중지시킴

guard condition else {
    statements
}

guard optionalBinding else {
    statements
}
func (id : String?) -> Bool {
    guard let id = id else {
        return false
    }
    guard id.count >= 6 else {
        return false
    }
    return true
}

validate(id : nil)          //false
validate(id : "abc")        //false
validate(id : "swiftlang")  //ture  

 

validate(id : nil)는 id = id 가 거짓이기 때문에 else 구문이 실행되고 Guard 문이 종료되고, validate(id : "abc")는 id = id 는 참이나 id.count >= 6이 거짓이므로 else 구문이 실행되고 종료되고 validate(id : "swiftlang")는 두 조건 식다 참이기 때문에 true를 리턴함

If vs Guard

func validateUsingIf() {
    var id : String? = nil

    if let str = id {
        if str.count >=6 {
            print(str)
        }
    }
}

func validateUsingGuard() {
    var id : String? = nil
    
    guard let str = id else { return }
    guard str.count >= 6 else { return }
    
    print(str)
}

 

If Guard
조건이 하나이거나 조건자체가 단순 
바인딩 한 상수를 다른 값을 처리하는 임시값으로 사용
중첩이 많아지면 가독성이 떨어짐
복잡한 조건을 여러개 구현
 바인딩한 상수를 동일한 스코프에서 계속해서 사용할 경우
가독성이 좋음