관리 메뉴

김종권의 iOS 앱 개발 알아가기

[iOS - swift] Switch-case문에서의 Optional Binding 방법 (none, some) 본문

iOS 응용 (swift)

[iOS - swift] Switch-case문에서의 Optional Binding 방법 (none, some)

jake-kim 2023. 6. 26. 01:11

Optional 타입

  • Optional 타입은 제네릭스를 받고, 그 제네릭스는 Optional 안에 감싼 값을 의미
  • Optional 타입은 enum이며, 2개의 case가 존재 
    • none: 값이 없는 case
    • some(Wrapped): 값이 있는 case
enum Optional<Wrapped>: ExpressibleByNilLiteral {
     case none
     case some(Wrapped)
 }
  • Wrapped는 값이라는 의미
  • swift 내부적으로 값이 없으면 none 케이스를 갖도록하고, 값이 있으면 some 케이스를 갖도록 구현한 것

Swift-case 문에서 Optional Binding 활용

  • Optional 타입은 none아니면 some인데, some 케이스에서는 값을 바로 접근할 수 있으므로 Optional Binding 된 값 사용이 가능
    • 엄밀히는 Optional binding이 아닌 switch - case문에서의 패턴매칭
let optionalString = Optional<String>("jake")

switch optionalString {
case .none:
    print("this is nil")
case let .some(value):
    print("some value = ", value)
}

// some value = jake
  • 패턴 매칭이 가능한 이유?
    • Optional 타입 코드를 들어가보면 안에서 패턴 매칭이 구현되어 있기 때문에 사용이 가능
    /// Returns a Boolean value indicating whether an argument matches `nil`.
    ///
    /// You can use the pattern-matching operator (`~=`) to test whether an
    /// optional instance is `nil` even when the wrapped value's type does not
    /// conform to the `Equatable` protocol. The pattern-matching operator is used
    /// internally in `case` statements for pattern matching.
    ///
    /// The following example declares the `stream` variable as an optional
    /// instance of a hypothetical `DataStream` type, and then uses a `switch`
    /// statement to determine whether the stream is `nil` or has a configured
    /// value. When evaluating the `nil` case of the `switch` statement, this
    /// operator is called behind the scenes.
    ///
    ///     var stream: DataStream? = nil
    ///     switch stream {
    ///     case nil:
    ///         print("No data stream is configured.")
    ///     case let x?:
    ///         print("The data stream has \(x.availableBytes) bytes available.")
    ///     }
    ///     // Prints "No data stream is configured."
    ///
    /// - Note: To test whether an instance is `nil` in an `if` statement, use the
    ///   equal-to operator (`==`) instead of the pattern-matching operator. The
    ///   pattern-matching operator is primarily intended to enable `case`
    ///   statement pattern matching.
    ///
    /// - Parameters:
    ///   - lhs: A `nil` literal.
    ///   - rhs: A value to match against `nil`.
    public static func ~= (lhs: _OptionalNilComparisonType, rhs: Wrapped?) -> Bool

 

  • none, some으로 케이스를 나누어서 사용하기도 하지만, 프로퍼티를 바로 선언하고 뒤에 '?'를 붙여서 더욱 간결하게 사용도 가능
    • .some(wrappedValue) 대신에 아래처럼 작성해도 접근이 가능 (위에서 살펴본 ~= 패턴 매칭 연산자가 내부적으로 구현되어 있기 때문에 아래처럼 사용도 가능한것)
switch optionalString {
case .none:
    print("this is nil")
case let unwrappedValue?:
    print("unwrappedValue = \(unwrappedValue)")
}
Comments