swift - 有没有办法减少 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)
结果没问题!我需要知道是否有更短的方法来编写代码,用循环或我不知道的东西减少行数。
解决方案
您的整个代码可以很简单:
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
.
推荐阅读
- python - python将位置从一个def导入另一个def以从天气API打印位置
- node.js - Express:用子资源定义 REST API?
- docker - Docker:如何将带有数据的容器从一台主机传输到另一台主机
- fortran - 在 Fortran90 内在函数上使用常规指令
- node.js - 将请求结果的第一部分通过管道传输到另一台主机
- javascript - Js错误:“未捕获(承诺)SyntaxError:输入意外结束”
- python - 在熊猫中按两列分组
- reactjs - auth.loginWithRedirect() 之后的 Auth0 重定向循环 - @auth0/auth0-spa-js
- regex - 匹配 Azure 负载均衡器名称的正则表达式
- javascript - 如何在默认情况下禁用按钮并在页面完全加载时启用它?