是否可以从枚举方法中更改枚举?

时间:2014-11-18 03:17:15

标签: swift enums

我在Swift中有一个枚举:

enum Orientation: Int
{
    case Rot_0 = 0, Rot_90, Rot_180, Rot_270

和我的枚举中的非静态方法,旨在顺时针或逆时针移动方向:

    func rotate(clockwise: Bool)
    {
        var nextRawValue = self.rawValue + (clockwise ? 1 : -1)

        if nextRawValue < Orientation.Rot_0.rawValue
        {
            nextRawValue = Orientation.Rot_270.rawValue
        }
        else if nextRawValue > Orientation.Rot_270.rawValue
        {
            nextRawValue = Orientation.Rot_0.rawValue
        }

        self = Orientation(rawValue: nextRawValue)
}

编译器告诉我你无法在方法中分配self。我无法理解为什么这是不可能的。

我唯一能想到的是使用静态方法rotate(orientation: Orientation, clockwise: Bool),但在这种情况下,必须将返回值显式地分配回枚举变量,这对我来说感觉就像编码错误。似乎说myOrientation.rotate()并且隐含地更改了值会更有用。

这个问题有一个优雅的解决方案吗?

谢谢你们!

1 个答案:

答案 0 :(得分:9)

当您要在方法中修改值类型(即structenum)时,您需要将其标记为mutating。这将使该方法可用于可变实例(使用var ...声明)但不是不可变实例(let ...):

mutating func rotate(clockwise: Bool)
{
    var nextRawValue = self.rawValue + (clockwise ? 1 : -1)

    if nextRawValue < Orientation.Rot_0.rawValue
    {
        nextRawValue = Orientation.Rot_270.rawValue
    }
    else if nextRawValue > Orientation.Rot_270.rawValue
    {
        nextRawValue = Orientation.Rot_0.rawValue
    }

    self = Orientation(rawValue: nextRawValue)!
}

请注意,修复变异错误会显示另一个 - Orientation(rawValue: nextRawValue)返回一个可选项,因此您需要先将其解包,然后才能分配给self。如果您已正确实现了先前的逻辑,那么使用强制解包运算符!应该是安全的。

相关问题