호댕의 iOS 개발

[Swift] Optional unwrapping 본문

Software Engineering/Swift

[Swift] Optional unwrapping

호르댕댕댕 2021. 10. 10. 22:45

평소 Optional 값은 풀기 귀찮은 값 정도로 생각하고 있었다. 왜 Optional 값을 사용해야 하는지 깊은 고민을 해보지 못했다. 그래서 이런 Optional 값에 대해 조금 더 이해를 해보고자 Swift Programming Language와 Apple Developer Document에서 Optional 관련 내용을 찾아봤다. 

 

Swift Programming Language를 보면 optional을 다음과 같은 경우에 사용한다고 말해주고 있다.
“You use optionals in situations where a value may be absent.”

 

The Basics — The Swift Programming Language (Swift 5.5)

The Basics Swift is a new programming language for iOS, macOS, watchOS, and tvOS app development. Nonetheless, many parts of Swift will be familiar from your experience of developing in C and Objective-C. Swift provides its own versions of all fundamental

docs.swift.org

 

 

The Basics — The Swift Programming Language (Swift 5.5)

The Basics Swift is a new programming language for iOS, macOS, watchOS, and tvOS app development. Nonetheless, many parts of Swift will be familiar from your experience of developing in C and Objective-C. Swift provides its own versions of all fundamental

docs.swift.org

즉, 값이 있을지, 없을지 모르는 상황에서 사용하는 것이다.

실제로 값이 없는 nil일 경우에 값을 꺼내오려고 하면 오류가 발생한다. 우리가 대부분 프로그램을 사용하다 프로그램이 갑자기 죽어버리는 경우도 nil 값을 꺼내오려다 발생한다.

그래서 Swift는 이런 상황을 최대한 방지하고자 C나 Objective-C에는 없는 옵셔널이란 개념을 사용한다.

값이 있을지, 없을지 모르는 것에 비닐 한겹을 감싸두는 것이다.

그렇다면 이러한 Optional 값을 어떻게 꺼낼 수 있을까?

  1. Optional Binding -> if let, guard let, switch를 사용해 unwrapping을 할 수 있다.
  2. 옵셔널 체이닝
  3. nil 병합 연산자 Nil-Coalescing Operator -> nil값을 어떻게 반환해줄지 정해줄 수 있다.
  4. Unconditional Unwrapping -> 비닐을 강제로 찢어버림, 100% 값이 있을 경우만 사용 (최대한 사용하지 말자)

 

1. Optional Binding

if let을 활용한 옵셔널 바인딩 

let userInput = readLine()

if let name = userInput {
	print("사용자 이름은 \(name)입니다")
}

guard let을 활용한 옵셔널 바인딩 

let userInput = readLine()

func print() {
    guard let input = userInput else {
        return
    }

    print ("사용자 이름은 \(input)입니다.")
}

print()

switch를 활용한 옵셔널 바인딩 

func printName() {
    switch userInput {
    case .some(let input):
        print("사용자 이름은 \(input)입니다.")
    default:
        print("입력 값이 없습니다.")
    }
}

printName()

 

2. 옵셔널 체이닝

옵셔널 체이닝이란 옵셔널 내부의 값이 있는지 매번 확인하지 않고 최종적으로 원하는 값을 확인할 때 유용하게 사용할 수 있다. 

 

3. Nil-Coalescing Operator

nil 값일 경우 어떤 값을 반환해줄지 미리 정해줄 수 있다. 

 

4. Unconditional Unwrapping

'!'를 사용하여 강제로 Optional 값을 unwrapping한다. 

Comments