我正在做一个棋盘游戏,你必须把两个物体连接起来。每个对象都有一个类型,有5个不同的类型。对于合并中的每一种不同类型的组合,游戏都会有不同的效果。现在,我正在处理每个组合的开关语句。所以,我的代码看起来就像这样。
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)合并具有相同的效果。是否有一个较少冗长的方法来实现这一点?
发布于 2017-03-28 00:56:25
不如:
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函数,以进一步减少每次所需的代码数量:
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语句中:
switch(object1.type,object2.type)
{
case (1,1):
doSome()
case (1,2),(2,1):
doSome2()
case (1,3),(3,1):
doSome3()
...
}更新
如果要以“置换不敏感”的方式比较两个以上的值,可以通过创建具有更多值的变体来扩展minMax()思想:
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
...
}}
发布于 2017-03-28 00:43:02
您可以传递多个逗号分隔的情况:
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"
}发布于 2017-03-28 01:42:46
您可以将对象抛到一个集合中(这本身就是无序的),并检查该集合是否包含一个元素组合。您有15 (5!= 5+4+3+2+1)情况,所以您将有15个ifs。
enum PrimaryColor {
case red, yellow, blue
}
enum SecondaryColor {
case orange, green, purple
init?(firstColor: PrimaryColor, secondColor: PrimaryColor) {
let colors = Set<PrimaryColor>([firstColor, secondColor])
if colors.contains(.red) && colors.contains(.blue) {
self = .purple
return
}
if colors.contains(.yellow) && colors.contains(.blue) {
self = .green
return
}
if colors.contains(.red) && colors.contains(.yellow) {
self = .orange
return
}
//if you care about the diagonal check firstColor == secondColor && colors.contains(.red) etc.
return nil
}
}https://stackoverflow.com/questions/43058699
复制相似问题