Swift - 多个交换机案例

Ala*_*ruz 10 switch-statement swift

我正在制作一个你必须加入两个物体的棋盘游戏.每个对象都有一个类型,有5种不同的类型.对于合并中的每种不同类型组合,将对游戏产生不同的影响.现在,我正在为每个组合使用switch语句.所以,我的代码看起来像这样.

struct Coin {
    var type = 1
}

// Each coin is of type Coin.   
switch(coin1.type, coin2.type) {
    case (1,1):
        functionNormal()
    case (1,2):
        functionUncommon()
    case (1,3):
        functionRare()
    ...
}
Run Code Online (Sandbox Code Playgroud)

对象的位置不会改变结果.(1,2)合并将具有与(2,1)合并相同的效果.是否有一种不那么冗长的方式来实现这一目标?

Ala*_* T. 20

怎么样 :

struct Object{
    var type = 1
}

let lowType  = min(object1.type,object2.type)
let highType = max(object1.type,object2.type)
switch( lowType, highType )
{
  case (1,1):
      doSome()
  case (1,2):
      doSome2()
  case (1,3):
    doSome3()
  ...
  // you will only need to specify the combinations where the first
  // type is less or equal to the other.
}
Run Code Online (Sandbox Code Playgroud)

请注意,您还可以将每个反转对放在其case语句中:

func minMax<T:Comparable>(_ a:T, _ b:T) ->(T,T) 
{ return a<b ? (a,b) : (b,a) }

switch minMax(object1.type,object2.type)
{
  case (1,1):
      doSome()
  case (1,2):
      doSome2()
  ...
Run Code Online (Sandbox Code Playgroud)


Joe*_*Joe 19

您可以将逗号分隔的多个案例传递给

   switch switchValue {
    case .none:
        return "none"
    case .one, .two:
        return "multiple values from case 2"
    case .three, .four, .five:
        return "Multiple values from case 3"
    }
Run Code Online (Sandbox Code Playgroud)