Reputation: 221
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 ?
Upvotes: 21
Views: 6835
Reputation: 2958
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")
}
}
}
Upvotes: 15
Reputation: 10896
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;
}
Upvotes: 4
Reputation: 22487
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
}
Upvotes: 3
Reputation: 53101
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)
}
Upvotes: 16