减少Swift中的括号数量

Byr*_*see 18 shorthand swift

有没有人知道是否有办法在swift中使用某种速记?更具体地说,在诸如IF语句之类的东西中省略括号......例如

if num == 0
  // Do something
Run Code Online (Sandbox Code Playgroud)

代替

if num == 0
{
  // Do something
}
Run Code Online (Sandbox Code Playgroud)

当你有几个嵌套的IF时,那些括号变得相当耗费空间.

PS.我知道我可以做到以下几点:

if num == 0 {
  // Do something }
Run Code Online (Sandbox Code Playgroud)

但是,如果可能的话,我仍然很好奇

Str*_*ara 64

你可以这样做:

let x = 10, y = 20;
let max = (x < y) ? y : x ; // So max = 20
Run Code Online (Sandbox Code Playgroud)

还有很多有趣的事情:

let max = (x < y) ? "y is greater than x" : "x is greater than y" // max = "y is greater than x"
let max = (x < y) ? true : false // max = true
let max = (x > y) ? func() : anotherFunc() // max = anotherFunc()
(x < y) ? func() : anotherFunc() // code is running func()
Run Code Online (Sandbox Code Playgroud)

以下堆栈:http://codereview.stackexchange.com可以更好地解决您的问题;)

编辑:小心三元运算符

通过使用if else语句替换三元运算符,构建时间减少了92.9%.

https://medium.com/@RobertGummesson/regarding-swift-build-time-optimizations-fc92cdd91e31#.42uncapwc

  • 你的例子是正确的,但要获得两个值的最大值,你可以使用`let maxValue = max(x,y)`max函数将返回最大值.所以,不要用它来获得两个整数的最大值 (2认同)