Optional은 스위프트에서 어떻게 구현 되어 있을까?

godo·2022년 11월 5일

인터뷰

목록 보기
1/1

정의

정의를 가서 찾아보면 ?

이런 식으로 enum 형으로 되어 있는 것을 볼 수 있습니다.

그리고 Generic 으로 되어 있어 어떠한 값도 받을 수 있습니다.

let optional: Optional<String> = nil

if optional = .none
if optional = .some(<#T##String#>)

따라서 이런 식으로도 사용할 수 있습니다.

정리 해보자면

Optional<T> = T?

Optonal.none = nil

init

생성자를 보면 저런식으로 되어 있습니다.

let `optional`: Optional<String> = .init("안녕하세요")

결과를 보면 이와 같이 나옵니다.

이 부분은 공식 문서에 보면 ExpressibleByNilLiteral 이라는 프로토콜 부분입니다.

간단하게 말하자면 nil 로 생성해줄 수 있는 프로토콜입니다.

map, flatmap

public func map<U>(_ transform: (Wrapped) throws -> U) rethrows -> U? {
  switch self {
    case .some(let y):
    	return .some(try transform(y)) // 다시 wrapping 해서 반환
    case .none:
    	return .none
  }
}

public func flatMap<U>(_ transform: (Wrapped) throws -> U?) rethrows -> U? {
  switch self {
    case .some(let y):
      return try transform(y) // 다시 wrapping 하지 않음
    case .none:
      return .none
  }
}

**Coalescing Nil Values**

public func ?? <T>(optional: T?, defaultValue: @autoclosure () throws -> T)
    rethrows -> T {
  switch optional {
  case .some(let value):
    return value
  case .none:
    return try defaultValue()
  }
}

b에 들어갈 내용은 @autoclosure로 선언되어 있어서 {}로 감싸지 않아도 자동으로 클로져로 취급됩니다.

Optional Pattern

Enumeration Case Pattern 이란

if case .some(let n) = optional {
    print(n)
}

Optional Pattern

if case let n? = optional { print(n) }

옵셔널 바인딩이 있는 데 왜 Optional Pattern ?

let variableList = [nil,2,3,4,nil,19,20,nil,46]

이런 nil 이 섞여 있는 배열이 있습니다.

바인딩을 사용하면 우리는 이런식으로 코드를 짜겠죠?

for number in variableList {
    guard let n = number else {continue}
    print(n)
}

그러나 옵셔널 패턴을 사용하면 ?

let variableList = [nil,2,3,4,nil,19,20,nil,46]

for case let number? in variableList {
    print(number)
}

이렇게 간단하게 코드를 짤 수 있습니다.

옵셔널을 유닛 테스트에서 활용하기

extension Optional where Wrapped == String {
    var empty: String {
        return self ?? ""
    }
}

이런식으로 Optional 을 익스텐션 합니다.

var testOption: Optional<String> = "테스트입니다"
print(testOption.empty)
testOption = nil
print(testOption.empty)

그리고 확인해 본다면 ?

이런식으로 나오게 됩니다.

이런것을 사용해 본다면 유닛 테스트 시 테스트하기 수월하게 됩니다.

reference

https://babbab2.tistory.com/132#:~:text=오홍!! Swift에서 Optional,구현이 되어 있구나!!

https://velog.io/@eddy_song/optional-under-the-hood

https://developer.apple.com/documentation/swift/optional

https://velog.io/@ericyong95/Swift-옵셔널Optional의-구현과-활용

https://daheenallwhite.github.io/swift/2019/07/08/Optional-is-Enumeration-Type/

https://developer.apple.com/documentation/swift/expressiblebynilliteral

profile
☀️☀️☀️

0개의 댓글