Raunak
Raunak

Reputation: 3414

Is it possible to create an optional literal in Swift?

I have explained my query in the code snippet below. I am looking for this type of syntax for Obj-C interoperability. Specifically I see a difference in behaviour of aCoder.encode(count, forKey: "count") API when count is Int (non-optional) vs Int? (optional)

import Foundation

let num = 5
// Swift's type system will infer this as Int (non-optional)
print(type(of: num))
// Prints: Int

let optNum: Int? = 5
// This is explicitly typed as an optional Int
print(type(of: optNum))
// Prints Optional<Int>

Is it possible to use a literal to implicitly type a var/let to optional?

// let imlicitOptional = 5?
// print(type(of: imlicitOptional))
// The above line should print: Optional<Int>

// or

// let imlicitOptional = num?
// print(type(of: imlicitOptional))
// The above line should print: Optional<Int>

Upvotes: 1

Views: 199

Answers (2)

Rico Crescenzio
Rico Crescenzio

Reputation: 4226

I don't know why you need this but you can do like this

let opt = 5 as Int?
// or
let opt = Optional(5)
// or
let opt = 5 as Optional // thanks to vacawama for this

Actually you can even create an operator that returns an optional but I think it's kinda useless.

postfix operator >?
postfix func >?<T>(value: T) -> T? {
    return Optional(value) // or return value as T?
}

let a = 5>?

Upvotes: 1

pacification
pacification

Reputation: 6018

Optional is a plain enum not any specific magic type. So, you can create a value using Optional:

let implicitOptional = Optional(5)
print(type(of: implicitOptional)) // Optional<Int>

Upvotes: 3

Related Questions