Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How are optional values implemented in Swift?

Tags:

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 ?

like image 725
Pierre Chatelier Avatar asked Jul 03 '14 08:07

Pierre Chatelier


People also ask

How does Swift handle optional value?

Optional Handling. In order to use value of an optional, it needs to be unwrapped. Better way to use optional value is by conditional unwrapping rather than force unwrapping using ! operator.

How the optional type is denoted in Swift?

An optional in Swift is basically a constant or variable that can hold a value OR no value. The value can or cannot be nil. It is denoted by appending a “?” after the type declaration.

Is optional value type in Swift?

Swift also introduces optional types, which handle the absence of a value. Optionals say either “there is a value, and it equals x” or “there isn't a value at all”. Optionals are similar to using nil with pointers in Objective-C, but they work for any type, not just classes.

What do optional types in Swift handle?

Optionals are in the core of Swift and exist since the first version of Swift. An optional value allows us to write clean code with at the same time taking care of possible nil values. If you're new to Swift you might need to get used to the syntax of adding a question mark to properties.


3 Answers

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)
}
like image 95
Ashley Mills Avatar answered Sep 22 '22 13:09

Ashley Mills


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")
        }
    }
}
like image 25
Ugo Arangino Avatar answered Sep 18 '22 13:09

Ugo Arangino


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
}
like image 27
Grimxn Avatar answered Sep 21 '22 13:09

Grimxn