首页 > 解决方案 > 有没有办法减少 Swift 代码行的数量?

问题描述

我刚刚开始学习 Swift,并在 Playground 中制作了一个轮盘赌类的应用程序。

我已经针对不同的场景和条件使用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):

依此类推,直到代码分别到达 case (36, 1) 和 case (36, 2)

结果没问题!我需要知道是否有更短的方法来编写代码,用循环或我不知道的东西减少行数。

标签: swift

解决方案


您的整个代码可以很简单:

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.


推荐阅读