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

Mic*_*man 2 enums swift

我在Swift中有一个枚举:

enum Orientation: Int
{
    case Rot_0 = 0, Rot_90, Rot_180, Rot_270
Run Code Online (Sandbox Code Playgroud)

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

    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)
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

多谢你们!

Nat*_*ook 9

当您要在方法中修改值类型(即struct或enum)时,需要将其标记为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)!
}
Run Code Online (Sandbox Code Playgroud)

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