본문 바로가기
TIL(Today I Learned)

2024.07.01 Today I Learned

by 승환파크 2024. 7. 1.

오늘은 챌린지반 수업을 듣기 전에 튜터님이 저번주에 숙제를 내주신 것이 있었다.

 

문제는 왼쪽의 사진을 보고 Optional(3) 으로 출력이 되는지 알아내야 하는 문제이다.

 

 

 

https://github.com/swiftlang/swift/blob/main/stdlib/public/core/Optional.swift <- 이곳에서 그 이유를 찾아야 한다.

 

이유를 찾아보니 Optional(3) 혹은 nil 이 반환되는 이유는 CustomDebugStringConvertible 프로토콜을 준수하기 때문이다. 이 프로토콜은 debugDescription 속성을 통해 객체의 문자열을 정의한다.

extension Optional: CustomDebugStringConvertible {
    public var debugDescription: String {
        switch self {
        case .some(let value):
            var result = "Optional("
            debugPrint(value, terminator: "", to: &result)
            result += ")"
            return result
        case .none:
            return "nil"
        }
    }
}

 

저 코드로 구현한 덕분에 print 함수를 사용할 때 Optional 값이 Optional(value) 형식으로 출력된다.

'TIL(Today I Learned)' 카테고리의 다른 글

2024.7.08 Today I Learned  (0) 2024.07.08
2024.07.04 Today I Learned  (0) 2024.07.05
2024.06.28 Today I Learned  (0) 2024.06.28
2024.06.27 Today I Learned  (0) 2024.06.27
2024.06.26 Today I Learned  (0) 2024.06.26