Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reducing the number of brackets in Swift

Tags:

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

instead of

if num == 0
{
  // Do something
}

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

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

like image 888
Byron Coetsee Avatar asked Jul 01 '14 09:07

Byron Coetsee


1 Answers

You can do that :

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

And so much interesting things :

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

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

Edit : ternary operators and compilation

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/regarding-swift-build-time-optimizations-fc92cdd91e31#.42uncapwc

like image 168
StrawHara Avatar answered Oct 12 '22 01:10

StrawHara