BossGiveMeArrays
BossGiveMeArrays

Reputation: 241

For Swift, is Double? the same as Optional<Double>?

    var title: Double? = nil
    var title2 = Optional<Double>.None

The two things above seem to both behave as optional Doubles. But when I hold option and click on title and title2, it shows that they have different types. One is Double? and the other is Optional<Double>. I'm just wondering if theres a difference between the two. And if they aren't different, why even have two of them? Was Optional an objective C thing that got transferred over to swift or something?

Upvotes: 2

Views: 167

Answers (1)

Martin R
Martin R

Reputation: 539735

There is no difference, and there is nothing special about Double here.

For any type T, T? is a (compiler built-in) shortcut for Optional<T>. So

var value: T?
var value: Optional<T>

are equivalent. Optional conforms to the NilLiteralConvertible protocol, i.e. a value can be instantiated from the literal nil, and

var value: T? = nil
var value: T? = .None
var value: T? = Optional.None
var value: T? = Optional<T>.None
var value: T? = T?.None

are all equivalent. In the first three statements, the type Optional<T> of the value on the right-hand side is inferred from the type annotation on the left-hand side. The last two statements can be shortened to

var value = Optional<T>.None
var value = T?.None

because the type is inferred automatically from the right-hand side.

Finally, since optionals are implicitly initialized to .None, all of the above statements are equivalent.

Upvotes: 3

Related Questions