我有3个屏幕的应用程序,屏幕1(类别)有多个按钮,屏幕2(详细信息)有更多按钮,屏幕3基于按钮是什么显示文本在前两个屏幕中按下。快速减少if语句的长度
屏幕1上的按钮保持不变,屏幕2上的按钮因隐藏或显示而异,具体取决于第一个屏幕上按下的按钮。为此,我现在有一个很长的陈述,我试图找到减少它的方法。
可以帮助,但认为我错过了简单的东西。
如果语句看起来类似于这样:
if selectedCategory == "Option 1" {
if selectedDetail == "Detail A" {
selectedURL = optionOneData.detailA
} else if selectedDetail == "Detail C" {
selectedURL = optionOneData.detailC
} else if selectedDetail == "Detail E" {
selectedURL = optionOneData.detailE
} else if selectedDetail == "Detail G" {
selectedURL = optionOneData.detailG
} else if selectedDetail == "Detail J" {
selectedURL = optionOneData.detailJ
} else {
print("Invalid selection, something went wrong.")
}
} else if selectedCategory == "Option 2" {
if selectedDetail == "Detail B" {
selectedURL = optionTwoData.detailB
} else if selectedDetail == "Detail C" {
selectedURL = optionTwoData.detailC
} else if selectedDetail == "Detail D" {
selectedURL = optionTwoData.detailD
} else if selectedDetail == "Detail E" {
selectedURL = optionTwoData.detailE
} else if selectedDetail == "Detail F" {
selectedURL = optionTwoData.detail F
} else if selectedDetail == "Detail G" {
selectedURL = optionTwoData.detailG
} else if selectedDetail == "Detail H" {
selectedURL = optionTwoData.detailH
} else if selectedDetail == "Detail I" {
selectedURL = optionTwoData.detailI
} else if selectedDetail == "Detail J" {
selectedURL = optionTwoData.detailJ
} else {
print("Invalid selection, something went wrong.")
}
不是我的实际代码,改名变量的上下文。
这只代表我所拥有的三分之一左右,所以我非常希望减少用于提高效率和可读性的代码量。
感谢。
'Switch()'语句替代了long if-elseif-else条件语句。尝试使用它。 – Priyal
也可以创建你的选项,因为'Enum'会使你的代码更具可读性,但你必须使用'switch'来分配数据和字符串 – Tj3n
switch语句仍然很长,你的数据可能被保存在字典中或阵列很容易。 –