我刚刚开始学习Swift,并在操场上制作了Roulette类的应用程序。
我在不同的情况和条件下使用了switch
和case
控制流。
我花了 156行来完成轮盘赌的全部36种可能性,当然还有红色和黑色。
有没有办法做到这一点?我做错了吗?
let number = Int.random(in: 0 ..< 37)
let color = Int.random(in: 1 ..< 3)
let NumberColor = (number, color)
let Red = "and the color is Red"
let Black = "and the color is Black"
switch NumberColor {
case (0, _):
print("The number is 0 and the color is Green!")
case (1, 1):
print("The Number is 1 \(Red)")
case (1, 2):
print("The Number is 1 \(Black)")
case (2, 1):
print("The Number is 2 \(Red)")
case (2, 2):
print("The Number is 2 \(Black)")
case (3, 1):
print("The Number is 3 \(Red)")
case (3, 2):
print("The Number is 3 \(Black)")
case (4, 1):
print("The Number is 4 \(Red)")
case (4, 2):
print("The Number is 4 \(Black)")
case (5, 1):
print("The Number is 5 \(Red)")
case (5, 2):
print("The Number is 5 \(Black)")
case (6, 1):
print("The Number is 6 \(Red)")
case (6, 2):
print("The Number is 6 \(Black)")
case (7, 1):
print("The Number is 7 \(Red)")
case (7, 2):
print("The Number is 7 \(Black)")
case (8, 1):
print("The Number is 8 \(Red)")
case (8, 2):
print("The Number is 8 \(Black)")
case (9, 1):
print("The Number is 9 \(Red)")
case (9, 2):
print("The Number is 9 \(Black)")
case (10, 1):
print("The Number is 10 \(Red)")
case (10, 2):
依次类推,直到代码分别到达大小写(36,1)和大小写(36,2)
结果还可以! 我需要知道是否有更短的代码编写方法,可以用循环或我不知道的东西减少行数。
答案 0 :(得分:6)
您的整个代码可以很简单:
let number = Int.random(in: 0 ..< 37)
let color = Int.random(in: 1 ..< 3)
print("The Number is \(number) and the color is \(color == 1 ? "Red" : "Black")")
就是这样。不需要元组或switch
。
答案 1 :(得分:0)
您可以将代码简化为:
let number = Int.random(in: 0 ... 36)
let color = Int.random(in: 1 ... 2)
switch (number, color) {
case (0, _):
print("The number is 0 and the color is Green!")
case (_, 1):
print("The number is \(number) and is Red")
case (_, 2):
print("The number is \(number) and is Black")
default:
break
}
现在,很明显,在实际的轮盘赌轮上,颜色和数字并不是像此代码所建议的那样独立,但这是一种简化代码同时又使意图清晰的方法。