Search code examples
swiftenums

How can I update enum type with a function in swift?


I have an enum which I want toggle it. with a code like this which is accessible from enum type itself, I tried using this code but did not solved the issue:

enum MyEnum {
    case yes
    case no
    
    mutating func toggle() {
        switch self {
        case .yes:
            MyEnum.no
        default:
            MyEnum.yes
        }
    }
}

func ff() {
    var test: MyEnum = MyEnum.yes
    test.toggle()
}

Solution

  • That code shouldn't even compile (unless you are testing in a playground) as you're not using MyEnum.no and MyEnum.yes in your toggle function.

    You simply need to assign the values to self to update the instance on which toggle is called.

    mutating func toggle() {
      switch self {
      case .yes:
        self = .no
      default:
        self = .yes
      }
    }