迅速的Xcode for循环阵列
问题描述:
我确实有下一个代码,它的工作,但i'm寻找一种方法,使之更加优雅迅速的Xcode for循环阵列
var collectionAnswers = [0,0,1]
if collectionAnswers[0] == 1 {
button1Oulet.backgroundColor = UIColor.green
} else {
button1Oulet.backgroundColor = UIColor.red
}
if collectionAnswers[1] == 1 {
button2Oulet.backgroundColor = UIColor.green
} else {
button2Oulet.backgroundColor = UIColor.red
}
if collectionAnswers[2] == 1 {
button3Oulet.backgroundColor = UIColor.green
} else {
button3Oulet.backgroundColor = UIColor.red
}
到目前为止,我已经来了下一个代码,但我可以“T使其工作
可以请你帮我,,,这里
样的卡for (index,element) in collectionAnswers.enumerated() {
switch index {
case 0, 1, 2:
if element == 0 {print("Bad")}
else {
for button in collectionOfButtons {
if index == button.tag && element == 1 {
button.backgroundColor = UIColor.green
} else {
button.backgroundColor = UIColor.red
}
}
print("OK")
}
default:
break
}
}
感谢您的帮助!
答
长话短说,创建一个包含按钮OU(T)的附加阵列允许
let collectionAnswers = [0, 0, 1]
let buttons = [button1Oulet, button2Oulet, button3Oulet]
for (index, answer) in collectionAnswers.enumerated() {
buttons[index].backgroundColor = (answer == 0) ? .red : .green
}
+0
谢谢你,,,完美的作品,我真的很感谢你的帮助 –
我投票作为题外话,因为它要求做一些工作的代码更优雅的关闭这个问题。这是代码评论网站的主题。 – dasblinkenlight
忘记if then else。使用一个Switch语句。 –