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
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)
}
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")
}
}
}
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
}
Most of the answers simply say that Swift optionals are implemented with enum
s which begs the questions of how then is are enum
s 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;
}