Swift中的单行if语句

Byt*_*Guy 36 objective-c ios swift swift3 swift4

如何从Objective-C将以下内容转换为Swift?

if (myVar) return;
Run Code Online (Sandbox Code Playgroud)

Swift不在条件周围使用括号,但是下面的代码给出了错误.

if myVar return 
Run Code Online (Sandbox Code Playgroud)

4aR*_*gh7 54

好吧,其他人也解释说,括号是必须迅速.但为了简单起见,我们可以做以下事情:

let a = -5

// if the condition is true then doThis() gets called else doThat() gets called
a >= 0 ? doThis(): doThat()

func doThis() {
    println("Do This")
}

func doThat() {
    println("Do That")
}
Run Code Online (Sandbox Code Playgroud)


Mic*_*lum 42

在Swift中,大括号不像Objective-C(C)那样是可选的.另一方面,parens是可选的.例子:

有效的Swift:

if someCondition {
    // stuff
}

if (someCondition) {
    // stuff
}
Run Code Online (Sandbox Code Playgroud)

无效的Swift:

if someCondition 
    // one liner

if (someCondition)
    // one liner
Run Code Online (Sandbox Code Playgroud)

这个设计决定消除了一整类错误,这些错误可能来自于不正确地使用if语句而没有大括号,如下面的情况,其中可能并不总是很清楚something值会有条件地改变,但是somethingElse每次都会改变值.

Bool something = true
Bool somethingElse = true

if (anUnrelatedCondition) 
    something = false
    somethingElse = false

print something // outputs true
print somethingElse // outputs false
Run Code Online (Sandbox Code Playgroud)

  • 与此相关的广泛公开的错误的一个例子是[Apple的SSL/TLS错误](https://www.imperialviolet.org/2014/02/22/applebug.html),而Swift正在开发中.我有时想知道这个设计决定是否是因为这个,或者它只是巧合.这是Swift的一个有趣的细节,因为"C like"语言强制执行编码风格的情况非常罕见. (7认同)

Azh*_*har 18

你可以使用新的Nil-Coalescing Operator,因为如果你需要在if if失败时只需设置默认值,就可以使用Swift 3:

let someValue = someOptional ?? ""
Run Code Online (Sandbox Code Playgroud)

如果someOptional是false,则此运算符将""赋给someValue

var dataDesc = (value == 7) ? "equal to 7" : "not equal to 7"
Run Code Online (Sandbox Code Playgroud)


Sul*_*han 13

许多开发人员认为单行if,单行while和单行for是一种不好的风格,因为它们的可读性较差,据称是许多错误的来源.

Swift通过禁止单行流控制语句解决了这个难题; 大括号是非选择性的......

if someCondition {
     // stuff
}
Run Code Online (Sandbox Code Playgroud)

当然,你仍然可以

if someCondition { return }
Run Code Online (Sandbox Code Playgroud)

还有实施原因.将条件括起来作为可选项使得解析更加困难.强制使用大括号可以再次简化解析.


Sat*_*man 10

这是我在项目中使用的简单解决方案.

Swift 4+

isManageCardTnCSelected ?
      (checkbox.isSelected = true) : (checkbox.isSelected = false)

var selected: Bool = isManageCardTnCSelected ?
      checkbox.isSelected = true : checkbox.isSelected = false
Run Code Online (Sandbox Code Playgroud)

Swift 3+

var retunString = (state == "OFF") ? "securityOn" : "securityOff"
Run Code Online (Sandbox Code Playgroud)