Swift - 多个开关盒 [英] Swift - Multiple Switch Cases
问题描述
我正在制作一个棋盘游戏,你必须连接两个对象.每个对象都有一个类型,有 5 种不同的类型.对于合并中的每种不同类型的组合,都会对游戏产生不同的影响.现在,我正在为每个组合使用 switch 语句.所以,我的代码看起来像这样.
I am making a board game where you must joins two objects. Each object has a type and there are 5 different types. For each different type combination in a merge, there will be a different effect on the game. Right now, I am working with a switch statement for each combination. So, my code would look something like this.
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()
...
}
对象的位置不会改变结果.(1,2) 合并与 (2,1) 合并具有相同的效果.有没有更简洁的方法来实现这一点?
The objects' position doesn't change the result. A (1,2) merge will have the same effect as a (2,1) merge. Is there a less verbose way to achieve this?
推荐答案
怎么样 :
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.
}
如果你经常这样做,你可以定义一个 minMax 函数来进一步减少每次所需的代码量:
If you will be doing this often, you could define a minMax function to further reduce the amount of code needed each time:
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()
...
请注意,您也可以将每个倒置对放在其 case 语句中:
note that you can also put each inverted pair in its case statement:
switch(object1.type,object2.type)
{
case (1,1):
doSome()
case (1,2),(2,1):
doSome2()
case (1,3),(3,1):
doSome3()
...
}
[更新]
如果您有两个以上的值要以排列不敏感"的方式进行比较,您可以通过创建具有更多值的变体来扩展 minMax() 的想法:
If you have more than two values to compare in a "permutation insensitive" fashion, you could expand on the minMax() idea by creating variants with more values:
func minToMax<T:Comparable>(_ a:T, _ b:T) -> (T,T)
{ return a<b ? (a,b) : (b,a) }
func minToMax<T:Comparable>(_ a:T, _ b:T, _ c:T) -> (T,T,T)
{ return { ($0[0],$0[1],$0[2]) }([a,b,c].sorted()) }
func minToMax<T:Comparable>(_ a:T, _ b:T, _ c:T, _ d:T) -> (T,T,T,T)
{ return { ($0[0],$0[1],$0[2],$0[3]) }([a,b,c,d].sorted()) }
switch minToMax(object1.type,object2.type,object3.type)
{
case (1,2,3) : doSome1() // permutations of 1,2,3
case (1,2,4) : doSome2() // permutations of 1,2,4
case (1,2,_) : doSome3() // permutations of 1,2,anything else
case (1,5...6,10) : doSome4() // more elaborate permutations
...
}
}
这篇关于Swift - 多个开关盒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!