[英]How do i write the if - else if code properly
I'm trying to make an if - else if statement writing two comparison operators in the 'else if' line (Int type).我正在尝试制作一个 if - else if 语句,在“else if”行(Int 类型)中写入两个比较运算符。 maybe is the syntax wrong?也许是语法错误?
i've tried to remove the parentheses from 'boysAge >= 21' but same results我试图从“boysAge >= 21”中删除括号,但结果相同
var boysAge = 21
var message = "The customer is "
if boysAge < 21 {
message += "underage"
}
else if (boysAge >= 21) && <70 {
message += "allowed"
}
print(message)
xcode says that '<' is not a prefix unary operator xcode 说 '<' 不是前缀一元运算符
var boysAge = 21
var message = "The customer is "
if boysAge < 21 {
message += "underage"
}
else if boysAge >= 21 && boysAge < 70 {
message += "allowed"
}
print(message)
You're missing a space between <
and 70
and you need to say what variable to check again, so boysAge < 70
.您在<
和70
之间缺少一个空格,您需要说明要再次检查的变量,因此boysAge < 70
。 Also the parentheses are unnecessary.括号也是不必要的。
Your code should work this way :您的代码应该这样工作:
if boysAge < 21 {
message += "underage"
}
else if boysAge < 70 {
message += "allowed"
}
If boysAge
is not strictly less than 21, then of course it's greater than or equal to 21
.如果boysAge
不严格小于 21,那么它当然大于或等于21
。 So you don't need to check it again.所以你不需要再次检查它。
Another way would be :另一种方法是:
if boysAge < 21 {
message += "underage"
}
else if 21..<70 ~= boysAge {
message += "allowed"
}
Using the ~=
operator.使用~=
运算符。
This seems to me like a great place to use switch case :在我看来,这是使用 switch case 的好地方:
switch boysAge {
case ...20:
message += "underage"
case 21..<70 :
message += "allowed"
default:
break
}
And you coud adjust the ranges to your liking.您可以根据自己的喜好调整范围。
The condition (boysAge >= 21) && <70
is not correct.条件(boysAge >= 21) && <70
不正确。 <
is a binary operator. <
是一个二元运算符。 That means it needs a left side and a right side.这意味着它需要一个左侧和一个右侧。 The correct way to write the condition is:写条件的正确方法是:
boysAge >= 21 && boysAge < 70
However, note that the boysAge >= 21
part is not necessary because it is already covered in the previous branch.但是请注意, boysAge >= 21
部分不是必需的,因为它已经在上一个分支中涵盖了。
var boysAge = 21
var message = "The customer is "
if boysAge < 21 {
message += "underage"
}
else if boysAge < 70 {
message += "allowed"
}
print(message)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.