减少Swift中的括号数量

时间:2014-07-01 09:41:23

标签: swift shorthand

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

if num == 0
  // Do something

而不是

if num == 0
{
  // Do something
}

当你有一些嵌套的IF时,这些大括号变得相当耗费空间。

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

if num == 0 {
  // Do something }

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

7 个答案:

答案 0 :(得分:63)

你可以这样做:

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可能更适合您的问题;)

编辑:小心使用三元运算符

  

除了用if else语句替换三元运算符之外,构建时间减少了92.9%。

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

答案 1 :(得分:4)

在swift中,即使在if:

中只有一个语句,你也必须添加大括号
if num == 0 {
  // Do something
}

你不能离开大括号,如果声明工作有多快。

答案 2 :(得分:3)

您可以像在objective-c中一样使用简写if语句:

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

答案 3 :(得分:3)

Swift 2.0更新 方法1:

scala> val b = B("B")
scala> val c = C("C")

scala> val newB = b.copy("B_new")
scala> newB.name // B_new

scala> val newC = c.copy("C_new")
scala> newC.name // C_new

方法2:如果

的简写
a != nil ? a! : b

Referance:Apple Docs: Ternary Conditional Operator

它确实有效,

b = a ?? ""

我用空字符串替换json字符串,如果它是nil。

编辑:添加 Gerardo Medina的建议...我们总是可以使用速记如果

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

答案 4 :(得分:1)

它被称为速记if-else条件。如果你是在Swift中进行iOS开发,那么你也可以操纵你的UI对象&#39;具有此属性的行为。

例如 - 我希望只有在文本字段中有一些文本时才能启用我的按钮。换句话说,当textfield中的字符数为零时,应该保持禁用状态。

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

答案 5 :(得分:1)

非常简单: 在Swift 4中

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

原始代码是

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

答案 6 :(得分:0)

您始终可以将整个if放在一行:

if num == 0 { temp = 0 }