如何在objective-c中写一行if语句?这有合适的风格吗?
我知道用于赋值(int a = condition ? b : c
)的三元运算符,但说我想调用一种方法if(condition){ [self methodCall]; }
推荐的在一行中处理此问题的方法吗?
此外,还有objc 风格指南吗?(想想这个红宝石风格指南)在一段时间没有接触它之后回到一门语言,这让我想重新思考如何设计我的代码。
三元 if 语句(if- else)
condition ? [self methodcall] : [self otherMethodCAll];
单一方法调用
if (condition) [self methodcall];
单行红宝石风格的if
和unless
语句在Objective-C中没有等价物。你可以坚持使用块,或者只在同一行上调用该方法:
if (condition) {
[self method];
}
或
if (condition)
[self method];
或
if (condition) [self method];
你不需要括号...
if(condition) [self methodCall];
这很简洁。
是的,在 Objective-C 中执行"单行if
语句"的唯一方法是将if
语句及其主体放在同一行上。