我知道在C#中使用Null合并运算符的标准方法是设置默认值.
string nobody = null;
string somebody = "Bob Saget";
string anybody = "";
anybody = nobody ?? "Mr. T"; // returns Mr. T
anybody = somebody ?? "Mr. T"; // returns "Bob Saget"
Run Code Online (Sandbox Code Playgroud)
但还有什么可以??用于?它不像三元运算符那样有用,除了比以下更简洁和更容易阅读:
nobody = null;
anybody = nobody == null ? "Bob Saget" : nobody; // returns Bob Saget
Run Code Online (Sandbox Code Playgroud)
所以考虑到甚至更少知道空合并运算符......
你有没有用过??别的东西?
是??必要的,还是应该只使用三元运算符(大多数人都熟悉)
c# null coding-style conditional-operator null-coalescing-operator
我在swift中有一个丑陋(但工作)的解包代码块:
var color = UIColor.whiteColor()
if ( label.backgroundColor? != nil )
{
color = label.backgroundColor!
}
Run Code Online (Sandbox Code Playgroud)
有没有更简洁的方式来编写这个在swift中像我在C++中一样?
UIColor color = (label.backgroundColor==nil) ?
UIColor.whiteColor() : label.backgroundColor;
Run Code Online (Sandbox Code Playgroud)