是否可以在 Swift 中创建可选文字?

Is it possible to create an optional literal in Swift?

我已经在下面的代码片段中解释了我的查询。我正在寻找这种类型的 Obj-C 互操作性语法。具体来说,当计数为 Int(非可选)与 Int 时,我看到 aCoder.encode(count, forKey: "count") API 的行为有所不同? (可选)

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>

是否可以使用字面量将 var/let 隐式键入可选?

// 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>

Optional 是普通的 enum 不是任何特定的魔法类型。因此,您可以使用 Optional:

创建一个值
let implicitOptional = Optional(5)
print(type(of: implicitOptional)) // Optional<Int>

我不知道你为什么需要这个,但你可以这样做

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

实际上你甚至可以创建一个 returns 可选的运算符,但我认为它有点没用。

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

let a = 5>?