How are optional values implemented in Swift?

前端 未结 4 444
广开言路
广开言路 2020-12-30 01:21

I wonder how the value types in Swift (Int, Float...) are implemented to support optional binding (\"?\"). I assume those value types are not allocated on the heap, but on t

4条回答
  •  萌比男神i
    2020-12-30 02:04

    Swift is open source since yesterday. You can see the implementation on GitHub: https://github.com/apple/swift/blob/master/stdlib/public/core/Optional.swift

    public enum Optional : ExpressibleByNilLiteral {
    
        case none
        case some(Wrapped)
    
        public init(_ some: Wrapped) { self = .some(some) }
    
        public init(nilLiteral: ()) {
            self = .none
        }
    
        public var unsafelyUnwrapped: Wrapped {
            get {
                if let x = self {
                    return x
                }
                _debugPreconditionFailure("unsafelyUnwrapped of nil optional")
            }
        }
    }
    

提交回复
热议问题