Reducing the number of brackets in Swift

前提是你 提交于 2019-12-03 07:56:44

问题


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


回答1:


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 : Be careful with ternary operator

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




回答2:


In swift you have to add braces even if there is just one statement in if:

if num == 0 {
  // Do something
}

You cannot leave the braces, that how swift if statement work.




回答3:


You could use a shorthand if statement like you would in objective-c:

num1 < num2 ? DO SOMETHING IF TRUE : DO SOMETHING IF FALSE



回答4:


Swift 2.0 update Method 1:

a != nil ? a! : b

Method 2: Shorthand if

b = a ?? ""

Referance: Apple Docs: Ternary Conditional Operator

and it does work,

u.dob = (userInfo["dob"] as? String) != nil ? (userInfo["dob"] as! String):""

I am replacing a json string with blank string if it is nil.

Edit: Adding Gerardo Medina`s suggestion...we can always use shorthand If

u.dob = userInfo["dob"] as? String ?? ""



回答5:


It is called shorthand if-else condition. If you are into iOS development in Swift, then you can also manipulate your UI objects' behaviour with this property.

For e.g. - I want my button to be enabled only when there is some text in the textfield. In other words, should stay disabled when character count in textfield is zero.

button.enabled = (textField.characters.count > 0) ? true : false




回答6:


its very simple : in Swift 4

    playButton.currentTitle == "Play" ? startPlay() : stopPlay()

Original Code is

    if playButton.currentTitle == "Play"{
     StartPlay()
    }else{
     StopPlay()
    }



回答7:


You could always put the entire if on one line:

if num == 0 { temp = 0 }


来源:https://stackoverflow.com/questions/24507072/reducing-the-number-of-brackets-in-swift

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!