我需要有一个嵌套的“ If语句”,并且不能完全正常工作-不断出现错误-在最后一个居里括号中正确显示期望的表达式。
下面的代码是我尝试过的:
if weightLabel.text == "Weight (lbs)" {
if pickerView == heightPicker {
let titleRow = height[row]
return titleRow
} else if pickerView == weightPicker {
let titleRow = weight[row]
return titleRow
}
return ""
else if weightLabel.text == "Weight (kgs)" {
if pickerView == heightPicker {
let titleRow = heightCM[row]
return titleRow
}
else if pickerView == weightPicker {
let titleRow = weightKG[row]
return titleRow
}
return ""
}
}
有人可以看看我当前的代码和帮助吗?
答案 0 :(得分:1)
应该是这样的:
func getWeight() -> String {
if weightLabel.text == "Weight (lbs)" {
if pickerView == heightPicker {
let titleRow = height[row]
return titleRow
}
else if pickerView == weightPicker {
let titleRow = weight[row]
return titleRow
}
return ""
}
else if weightLabel.text == "Weight (kgs)" {
if pickerView == heightPicker {
let titleRow = heightCM[row]
return titleRow
}
else if pickerView == weightPicker {
let titleRow = weightKG[row]
return titleRow
}
return ""
}
return ""
}
答案 1 :(得分:0)
由于到处都有return语句,因此可以跳过所有else
if weightLabel.text == "Weight (lbs)" {
if pickerView == heightPicker {
return height[row]
}
if pickerView == weightPicker {
return weight[row]
}
}
if weightLabel.text == "Weight (kgs)" {
if pickerView == heightPicker {
return heightCM[row]
}
if pickerView == weightPicker {
return weightKG[row]
}
}
return ""
另一种方法是使用在if / else子句中设置的局部变量,然后返回
var titleRow = ""
if weightLabel.text == "Weight (lbs)" {
if pickerView == heightPicker {
titleRow = height[row]
} else if pickerView == weightPicker {
titleRow = weight[row]
}
} else if weightLabel.text == "Weight (kgs)" {
if pickerView == heightPicker {
titleRow = heightCM[row]
} else if pickerView == weightPicker {
titleRow = weightKG[row]
}
}
return titleRow