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)))!
}
}
我是 swift 的新手,但我有很多编程经验。但是,在 Swift 中处理未知数时,我从未遇到过类似变量“wrapping”的情况。
我有一个静态函数 random,它返回一个 Orientation。 Orientation 类没有任何可选内容。但是,我必须在随机函数的返回语句上使用感叹号。
这是为什么?请原谅我完全缺乏关于 swift 的知识。
最佳答案
很明显,初始化器可能会失败。让我们假设:
Orientation(rawValue: 10)
这不会在您的枚举中找到值,那么您希望它返回什么?它将返回 nil
。这意味着返回值必须是可选的,因为可以返回 nil
。
Swift Language Guide 中明确提到了这一点, 枚举, 从原始值初始化:
NOTE
The raw value initializer is a failable initializer, because not every raw value will return an enumeration member. For more information, see Failable Initializers.
但是,在这种情况下(方法 random
)您确定不会返回 nil
,因此最好的解决方案是在返回之前解包可选来自随机
。
关于ios - 为什么我需要解包这个变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27219757/