How are optional values implemented in Swift?

前端 未结 4 421
广开言路
广开言路 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条回答
  • 2020-12-30 02:00

    Optionals are implemented as enum type in Swift.

    See Apple's Swift Tour for an example of how this is done:

    enum OptionalValue<T> {
        case None
        case Some(T)
    }
    
    0 讨论(0)
  • 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<Wrapped> : 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")
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-30 02:08

    Optionals are implemented as shown below. To find this, CMD-Click on a declaration like var x: Optional<Int>. var x: Int? is just syntactic sugar for that.

    enum Optional<T> : LogicValue, Reflectable {
        case None
        case Some(T)
        init()
        init(_ some: T)
    
        /// Allow use in a Boolean context.
        func getLogicValue() -> Bool
    
        /// Haskell's fmap, which was mis-named
        func map<U>(f: (T) -> U) -> U?
        func getMirror() -> Mirror
    }
    
    0 讨论(0)
  • 2020-12-30 02:10

    Most of the answers simply say that Swift optionals are implemented with enums which begs the questions of how then is are enums implemented. Something akin to tagged unions in C must be used. For example, the Swift enum

    enum Foo {
      case None
      case Name(String)
      case Price(Double)
    }
    

    could be mimick'ed in C as follows:

    enum {FOO_NONE_, FOO_NAME_, FOO_PRICE_};
    typedef struct {
       int flavor; // FOO_NONE_, FOO_NAME_ or FOO_PRICE_
       union {
          char *Name;  // payload for FOO_STRING_
          double Price; // payload for FOO_DOUBLE_
       } u;
    } 
    
    0 讨论(0)
提交回复
热议问题