减少Swift中的括号数量 [英] Reducing the number of brackets in Swift

查看:83
本文介绍了减少Swift中的括号数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人知道是否有一种快速使用某种速记方式的方法吗?更具体地说,在诸如IF语句之类的东西中省去大括号...例如

Does anyone know if there is a way to use some kind shorthand in swift? more specifically, leaving out the braces in things like IF statements... eg

if num == 0
  // Do something

代替

if num == 0
{
  // Do something
}

当您有一些嵌套的IF时,这些花括号会占用相当大的空间.

Those braces become rather space consuming when you have a few nested IF's.

PS.我知道我可以执行以下操作:

PS. I do know I can do the following:

if num == 0 {
  // Do something }

但是我仍然很好奇这种事情是否可能

But I'm still curious if that sort of thing is possible

推荐答案

您可以这样做:

let x = 10, y = 20;
let max = (x < y) ? y : x ; // So max = 20

很多有趣的事情:

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()

以下堆栈: http://codereview.stackexchange.com 对于您的问题可能会更好;)

This following stack : http://codereview.stackexchange.com can be better for your question ;)

三元运算符和编译

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

By doing nothing more than replacing the ternary operator with an if else statement, the build time was reduced by 92.9%.

https://medium.com/@ RobertGummesson/关于快速构建时间优化-fc92cdd91e31#.42uncapwc

这篇关于减少Swift中的括号数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆