swift Optional Binding 공식문서 읽어보기

Hashswim·2023년 10월 17일
0

if 구문은 if 뒤의 조건문이 참/거짓에 따라 분기 처리를 하는 구문으로 대부분 사람들에게 익숙하다..

그러다 문득 if let 바인딩과 섞어 쓸 때는 어떻게 동작하는지 자세히 알아보고 싶어졌다.

You can use both constants and variables with optional binding.

If you wanted to manipulate the value of myNumber within the first branch of the if statement, you could write if var myNumber instead, and the value contained within the optional would be made available as a variable rather than a constant.

Changes you make to myNumber inside the body of the if statement apply only to that local variable, not to the original, optional constant or variable that you unwrapped.

You can include as many optional bindings and Boolean conditions in a single if statement as you need to, separated by commas.
If any of the values in the optional bindings are nil or any Boolean condition evaluates to false, the whole if statement’s condition is considered to be false. The following if statements are equivalent:

공식 문서를 읽어보니

  • 옵셔널 바인딩은 변수와 상수 모두 사용 가능하다

  • 할당 하는 부분을 생략할 수 있다 (처음 알았다;;)
    (if let myNumber = myNumber {statement} 대신 if let myNumber {statement}로 축약)

  • 여러개의 옵셔널 바인딩과 Boolean condition들을 ,를 사용해 나열할 수 있다.

아래의 두 코드가 동일하다는 예제인데...

if let firstNumber = Int("4"), let secondNumber = Int("42"), firstNumber < secondNumber && secondNumber < 100 {
    print("\(firstNumber) < \(secondNumber) < 100")
}
if let firstNumber = Int("4") {
    if let secondNumber = Int("42") {
        if firstNumber < secondNumber && secondNumber < 100 {
            print("\(firstNumber) < \(secondNumber) < 100")
        }
    }
 }

옵셔널 바인딩, 옵셔널 바인딩, Boolean expression으로 나열되어 있다.

같은 결과야 이해되지만 선언된 firstNumber와 secondNumber을 바로 같은 라인에서 사용할 수 있는것이 의문이다.

또 옵셔널 바인딩이 참과 거짓의 Bool타입으로 처리된다면

if let firstNumber = Int("4") && let secondNumber = Int("42") && (firstNumber < secondNumber && secondNumber < 100)

이렇게도 사용이 가능한가??(안됨)

조금 헷갈려서 관련된 내용을 공식문서에서 찾아보았다...
다음 포스트로😙

0개의 댓글