2014-09-22 41 views
1

我目前很新的雨燕,我想知道,如果下面的代码可以被优化/缩短以任何方式:交换枚举值斯威夫特

enum CardOrientation { 
    case Horizontal, Vertical 
} 

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

让我们假设CardOrientation将永远只是有这些两个可能的值和每个呼叫toggleCurrentCardOrientation都应该在每个值之间切换。

回答

4

两个可能的解决方案:

使用布尔代替(如isCardOrientationHorizo​​ntal)

BOOLS都极为方便切换:isCardOrientationHorizontal = !isCardOrientationHorizontal

添加一个切换到你的枚举的方法:

enum CardOrientation { 
    case Horizontal, Vertical 

    mutating func toggle() { 
     switch self { 
      case .Horizontal: 
       self = .Vertical 
      case .Vertical: 
       self = .Horizontal 
     } 
    } 
} 
+0

+1提供两种不同的方法。起初我正在考虑使用Bool,但我总觉得能够使用令人敬畏的“.Vertical”语法,这使得它更加明显地发生了什么。 – BastiBen 2014-09-22 17:13:39

1

我会将切换方法移到枚举本身。然后将该方法标记为mutating以通过更新自身来祝福它。考虑到只有两个选项,switch看起来像是过度杀伤。您只能使用if/else。但如果你有两个以上的选项,switch更有意义。

例如:

enum CardOrientation { 
    case Horizontal, Vertical 
    mutating func toggle() { 
     if self == .Horizontal { 
      self = .Vertical 
     } else { 
      self = .Horizontal 
     } 
    } 
} 

var currentCardOrientation: CardOrientation = .Horizontal 
currentCardOrientation.toggle() 
currentCardOrientation // .Vertical 
currentCardOrientation.toggle() 
currentCardOrientation // .Horizontal 
+0

我会说,如果他在将来增加另一个案例时,开关优于if语句。将编译器作为安全网,以确保所有案例都被考虑在内是最好的。 – drewag 2014-09-22 17:05:40

+0

你可能是对的。 – 2014-09-22 17:06:25

+0

@drewag,一般来说这是真的,但如果使用“切换”功能,超过两个就没什么意义了。 – 2014-09-22 17:06:48

0

好了,你可以定义枚举本身

enum CardOrientation { 
    case Horizontal, Vertical 

    func swap() -> CardOrientation { 
     switch(self) { 
     case Horizontal: return Vertical 
     case Vertical: return Horizontal 
     } 
    } 
} 

swap功能,并使用它像

func toggleCurrentCardOrientation() { 
    currentCardOrientation = currentCardOrientation.swap() 
} 

作为个人风格而言,我宁愿不变异的实例本身,因为引入可变状态使代码的推理越来越困难。

0

在我看来,本质上可翻转的enum应该有相同的原始值与同样的特质。由于Bool不能用作原始类型(你的第一本能),这个怎么样?

enum CardOrientation: Int { 
    case Horizontal = -1, Vertical = 1 

    mutating func toggle() { 
     self = CardOrientation.fromRaw(-self.toRaw())! 
    } 
} 

在一个侧面说明...对于Bool不能够用作以下用途─原因“原始类型‘布尔’是不可自由兑换的任何文字” -might是因为truefalse成了文字中的错误其中一个测试版。