我应该总是用 Swift 中的三元替换 if...then...else 吗?
Should I always replace if...then...else with a ternary in Swift?
如果我可以用三元替换 if...then...else
,我应该这样做吗?或者归结为两者中哪一个最容易阅读和清楚?
例如变化:
If condition {
doSomething
} else {
doSomethingElse
}
到
condition ? doSomething : doSomethingElse
如何使用变量赋值:
If condition {
myProperty += 1
} else {
myProperty -= 1
}
至:
myProperty = condition ? myProperty + 1 : myProperty - 1
编辑:不是在寻找人们更喜欢的意见,而是在寻找是否有公认的专业实践来替换 if...then...else 如果可能的话。
没有。三元运算符应该只用于 select 两个表达式之一的值。如果您的论点是 "nouns",则认为它是合适的。例如:
let wheels = isTricycle ? 3 : 2
在执行操作或具有更复杂参数的情况下,使用传统的 if
语句。
Apple 在 iBook "The Swift Programming Language" 中说了很多,只提供了这些类型的三元运算符示例,并特别指出:
“The ternary conditional operator provides an efficient shorthand for deciding which of two expressions to consider. Use the ternary conditional operator with care, however. Its conciseness can lead to hard-to-read code if overused.”
摘自:Apple Inc.“Swift 编程语言(Swift 2 预发行版)。”电子书。
由于两者都是有效的并且在性能上没有差异,所以目标是可读性。
使用三元条件进行简单的内联决策。
对于任何不适合内联或比基本算术更复杂的内容,使用普通条件语句可能更具可读性
Apple 在 Swift 2.2 文档中有一个很好的例子
示例来自 Swift 2.2 Apple 文档:
let contentHeight = 40
let hasHeader = true
let rowHeight = contentHeight + (hasHeader ? 50 : 20)
// rowHeight is equal to 90
我想说上面的内容和下面的一样可读,而且更清晰。
let contentHeight = 40
let hasHeader = true
let rowHeight: Int
if hasHeader {
rowHeight = contentHeight + 50
} else {
rowHeight = contentHeight + 20
}
// rowHeight is equal to 90
如果我可以用三元替换 if...then...else
,我应该这样做吗?或者归结为两者中哪一个最容易阅读和清楚?
例如变化:
If condition {
doSomething
} else {
doSomethingElse
}
到
condition ? doSomething : doSomethingElse
如何使用变量赋值:
If condition {
myProperty += 1
} else {
myProperty -= 1
}
至:
myProperty = condition ? myProperty + 1 : myProperty - 1
编辑:不是在寻找人们更喜欢的意见,而是在寻找是否有公认的专业实践来替换 if...then...else 如果可能的话。
没有。三元运算符应该只用于 select 两个表达式之一的值。如果您的论点是 "nouns",则认为它是合适的。例如:
let wheels = isTricycle ? 3 : 2
在执行操作或具有更复杂参数的情况下,使用传统的 if
语句。
Apple 在 iBook "The Swift Programming Language" 中说了很多,只提供了这些类型的三元运算符示例,并特别指出:
“The ternary conditional operator provides an efficient shorthand for deciding which of two expressions to consider. Use the ternary conditional operator with care, however. Its conciseness can lead to hard-to-read code if overused.”
摘自:Apple Inc.“Swift 编程语言(Swift 2 预发行版)。”电子书。
由于两者都是有效的并且在性能上没有差异,所以目标是可读性。
使用三元条件进行简单的内联决策。
对于任何不适合内联或比基本算术更复杂的内容,使用普通条件语句可能更具可读性
Apple 在 Swift 2.2 文档中有一个很好的例子
示例来自 Swift 2.2 Apple 文档:
let contentHeight = 40
let hasHeader = true
let rowHeight = contentHeight + (hasHeader ? 50 : 20)
// rowHeight is equal to 90
我想说上面的内容和下面的一样可读,而且更清晰。
let contentHeight = 40
let hasHeader = true
let rowHeight: Int
if hasHeader {
rowHeight = contentHeight + 50
} else {
rowHeight = contentHeight + 20
}
// rowHeight is equal to 90