2016-12-22 34 views
0

以下代码像红绿灯一样运行。红色 - >黄色 - >绿色。我的代码如何编写,以便当“else if timerInt == 0 {”来自r.png或yellow.png时出现。基本上硬币会翻转,r或黄色都会出现。但机会是平等的,而且总是随机的。谢谢如何创建随机化的if else语句swift 3

timerInt -= 1 
    if timerInt == 2{ 
     light.image = UIImage(named: "r.png") 
    } else if timerInt == 1 { 
     light.image = UIImage(named: "yellow.png") 
    } else if timerInt == 0 { 
     light.image = UIImage(named: "g.png") 
    } 

回答

2

您需要在if timerInt == 0块中添加其他条件。这个if语句将使用arc4random_uniform(upperBound),产生一个随机数

upperBound介于0和

light.image = UIImage(named: arc4random_uniform(2) == 0 ? "r.png" : "yellow.png") 

在这里,我使用内联三元运算符if语句。如果条件得到满足,则将评估第一个表达式,否则将是较晚的表达式。

+0

我会写这样的:'light.image = UIImage(named:arc4random_uniform(2)== 0?“r”:“yellow”)' – rmaddy

+1

\ _(ツ)_ /¯在生产代码中,I 'd当然在资源命名空间中有这些图像,所以更可能'light.image = arc4random_uniform(2)== 0? Resource.Image.redLight:Resource.Image.yellowLight'。但是,在这里它可能是有道理的。 – tomahh