Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
我会倾向于
if (object == nil)
但我注意到在一些教程中使用
if (nil == object)
这只是一种风格,还是使用任何一种格式都有合理的理由?
这通常是为了防止使用赋值运算符而不是比较运算符。例如,如果您不小心输入了这个:
if (object = nil)
它可能会编译,但这不是您想要的。
通过使用第二种形式,如果您输入错误,您将确保编译时错误,因为 nil 不能用作赋值中的左操作数。
请注意,我不是一个客观的 C 程序员,但这个问题对于很多语言来说都是通用的。
该if (nil == object)版本可以更好地保护您,以防您不小心输入 = 而不是 ==。