Swift中的if或and/or语句如何像Python一样使用

31 投票
2 回答
74747 浏览
提问于 2025-04-28 11:11

在Swift中,有没有办法在if语句里使用“与”或者“或”的意思?比如说:

if a > 0 and i == j or f < 3:
    //do something 

我们可以在Swift里这样做吗?

提前谢谢你!

暂无标签

2 个回答

8

是的。

if (a > 0 && i == j || f < 3){
    //do something
}

在开始之前,你可能应该先了解一下Swift的基础知识。里面会讲到if语句。

56

你可以使用


&&

来表示逻辑与


|| 

来表示逻辑或


所以你可以这样做

if a > 0 && i == j || f < 3 {
    ...
}

想了解更多,可以查看这里:

https://developer.apple.com/library/ios/documentation/swift/conceptual/Swift_Programming_Language/BasicOperators.html

撰写回答