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 ?
Asked
Active
Viewed 5,881 times
21
-
Bonus : whoever knowns the answer : how and where can we find such an answer for a given Swift seed (just in case of change in the future) – Pierre Chatelier Jul 03 '14 at 08:39
-
possible duplicate of [What does an exclamation mark mean in the Swift language?](http://stackoverflow.com/questions/24018327/what-does-an-exclamation-mark-mean-in-the-swift-language) – Sulthan Jul 03 '14 at 08:40
4 Answers
16
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)
}

Ashley Mills
- 50,474
- 16
- 129
- 160
-
-
10and then I guess the question would be... how are enums implemented? :) – newacct Jul 03 '14 at 18:19
-
I imagine that *tagged unions* are used which means that every value has a related tag stored with it. How else could you store a `Double?` ? – wcochran Jan 08 '16 at 01:21
15
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")
}
}
}

Ugo Arangino
- 2,802
- 1
- 18
- 19
-
All this to use an `var theOptionalInt: Int?`? Grossly inefficient compared to `int theInteger = 0;` or even `var theInteger: Integer = 0;` although thanks for posting Ugo... it’s kind of a shocker. Even AppleScript is more efficient. – Cerniuk Oct 14 '18 at 14:29
4
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;
}

wcochran
- 10,089
- 6
- 61
- 69
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
}