为什么我需要打开这个变量?

Jax*_*xkr 3 xcode ios swift

import SpriteKit

let NumOrientations: UInt32 = 4

enum Orientation: Int, Printable {
case Zero = 0, Ninety, OneEighty, TwoSeventy

var description: String {
    switch self {
        case .Zero:
            return "0"
        case .Ninety:
            return "90"
        case .OneEighty:
            return "180"
        case .TwoSeventy:
            return "270"
    }
}

static func random() -> Orientation {
    return Orientation(rawValue: Int(arc4random_uniform(NumOrientations)))!
}
}
Run Code Online (Sandbox Code Playgroud)

我是swift的新手,但我有很多编程经验.但是,在处理Swift中的未知数时,我从未遇到过类似变量"换行"的东西.

我有静态函数random,它返回一个Orientation.Orientation类没有任何可选项.但是,我必须在随机函数的return语句中使用感叹号.

为什么是这样?请原谅我对swift完全缺乏了解.

Sul*_*han 5

好吧,显然初始化程序可能会失败.我们假设:

Orientation(rawValue: 10)
Run Code Online (Sandbox Code Playgroud)

这不会在你的枚举中找到一个值,那么你期望它返回什么?它会回来nil.这意味着返回值必须是可选的,因为nil可以返回.

这在Swift语言指南,枚举,从原始值初始化中明确提到:

注意

原始值初始化程序是一个可用的初始化程序,因为并非每个原始值都将返回枚举成员.有关更多信息,请参阅Failable Initializers.

但是,在这种情况下(方法random),您确定nil不会返回a,因此最好的解决方案是在返回之前解包可选项random.