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 ?
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.
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.
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.
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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With