Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swapping an enum value in Swift

Tags:

swift

I'm currently very new to Swift and I was wondering if the following code can be optimized/shortened in any way:

enum CardOrientation {
    case Horizontal, Vertical
}

func toggleCurrentCardOrientation() {
    switch currentCardOrientation {
    case .Horizontal: currentCardOrientation = .Vertical
    case .Vertical: currentCardOrientation = .Horizontal
    }
}

Let's assume that CardOrientation will always just have these two possible values and every call to toggleCurrentCardOrientation should toggle between each of those.

like image 511
BastiBen Avatar asked Sep 22 '14 16:09

BastiBen


1 Answers

Two possible solutions:

Use a Bool instead (e.g. isCardOrientationHorizontal)

Bools are extremely easy to toggle: isCardOrientationHorizontal.toggle()

Add a toggle method to your enum:

enum CardOrientation {
    case Horizontal, Vertical

    mutating func toggle() {
        switch self {
            case .Horizontal:
                self = .Vertical
            case .Vertical:
                self = .Horizontal
        }
    }
}
like image 138
drewag Avatar answered Oct 17 '22 07:10

drewag