我正在为if语句中的单个变量设置多个整数测试.逻辑运算符不能工作,因为它们必须是布尔值.
例如:
if self.nodeAtPoint(location) == self.fake { groundspeed = 35.0 self.button1value++ if(button1value == 2) { groundspeed = 5.0 } if(button1value == 4){ groundspeed = 5.0 } if(button1value == 6) { groundspeed = 5.0 } }
目标是将所有偶数显示在一个if语句中.
如果我们只想检查button1value是否为偶数,我们可以使用模(%)运算符:
if button1value % 2 == 0 { // button1value is even groundspeed = 5.0 }
如果我们检查一些其他类型的集合,我们可以使用switch语句:
switch button1value { case 2,4,6: // button1value is 2,or 6 groundspeed = 5.0 default: // button1value is something else }
如果我们想要的话,我们也可以使用Swift的switch语句来做其他整洁的技巧:
switch (button1value % 2,button1value % 3) { case (0,0): // button1value is an even multiple of 3 (6,12,18...) case (0,_): // button1value is an even number not a multiple of three (2,8,10,14...) case (_,0): // button1value is an odd multiple of three (3,9,15,21...) default: // button1value is none of the above: (1,5,7,11...) }