Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to change an enum from inside an enum method?

Tags:

enums

swift

I have an enum in Swift:

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

and a non-static method within my enum designed to shift the orientation clockwise or counterclockwise:

    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)
}

The the compiler is telling me that you cannot assign to self in a method. I'm having trouble understanding why this isn't possible.

The only thing I can think of is having a static method rotate(orientation: Orientation, clockwise: Bool), but in this case, the return value must be explicitly assigned back to the enum variable, and that just feels like bad coding to me. It seems like it would be much more useful to say myOrientation.rotate() and have the value changed implicitly.

Is there an elegant solution to this problem?

Thanks guys!

like image 612
Michael Zimmerman Avatar asked Nov 30 '25 06:11

Michael Zimmerman


1 Answers

When you're going to modify a value type (i.e., struct or enum) in a method, you need to mark it as mutating. This will make the method usable by mutable instances (declared with var ...) but not immutable instances (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)!
}

Note that fixing the mutating error reveals another -- Orientation(rawValue: nextRawValue) returns an optional, so you need to unwrap it before you can assign to self. If you've implemented the prior logic correctly, you should be safe in using the force unwrapping operator !.

like image 152
Nate Cook Avatar answered Dec 02 '25 04:12

Nate Cook



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!