How are optional values implemented in Swift?

眉间皱痕 提交于 2019-12-18 12:13:09

问题


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 the stack. So, do they rely on some kind of pointer to the stack that may be null, or does the underlying struct contain a boolean flag ?


回答1:


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)
}



回答2:


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")
        }
    }
}



回答3:


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
}



回答4:


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;
} 


来源:https://stackoverflow.com/questions/24548475/how-are-optional-values-implemented-in-swift

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!