var num: Int? = 3
print(num)
//결과값: Optional("3")
에서 왜 출력값이 Optional("3")로 나오는지 이유를 찾아보라는 과제를 받았다.
처음 들었을때 뭔 1 + 1이 2인 이유를 증명하라와 비슷한 느낌을 받았는데 좀 찾아보니
@frozen
public enum Optional<Wrapped: ~Copyable>: ~Copyable {
// The compiler has special knowledge of Optional<Wrapped>, including the fact
// that it is an `enum` with cases named `none` and `some`.
/// The absence of a value.
///
/// In code, the absence of a value is typically written using the `nil`
/// literal rather than the explicit `.none` enumeration case.
case none
/// The presence of a value, stored as `Wrapped`.
case some(Wrapped)
}
일단 옵셔널은 이렇게 case none 과 some(Wrapped)로 이루어진 enum이라는것을 알았다.
@_unavailableInEmbedded
extension Optional: CustomDebugStringConvertible {
/// A textual representation of this instance, suitable for debugging.
public var debugDescription: String {
switch self {
case .some(let value):
#if !SWIFT_STDLIB_STATIC_PRINT
var result = "Optional("
#if !$Embedded
debugPrint(value, terminator: "", to: &result)
#else
_ = value
"(cannot print value in embedded Swift)".write(to: &result)
#endif
result += ")"
return result
#else
return "(optional printing not available)"
#endif
case .none:
return "nil"
}
}
}
이 코드 때문이다
A textual representation of this instance, suitable for debugging
.some case 에서 "Optional(" ")"을 value 앞 뒤로 붙여준 코드다
https://github.com/swiftlang/swift/blob/main/stdlib/public/core/Optional.swift 자세한 내용은 여기로
퍼가요~