控制流/Control Flow

Prefer the for-in style of for loop over the while-condition-increment style.

优先选择 for 循环的 for-in 格式而不是 while-condition-increment 风格的循环。

推荐(Preferred):

for _ in 0..<3 {
  print("Hello three times")
}

for (index, person) in attendeeList.enumerated() {
  print("\(person) is at position #\(index)")
}

for index in stride(from: 0, to: items.count, by: 2) {
  print(index)
}

for index in (0...3).reversed() {
  print(index)
}

不推荐(Not Preferred):

var i = 0
while i < 3 {
  print("Hello three times")
  i += 1
}

var i = 0
while i < attendeeList.count {
  let person = attendeeList[i]
  print("\(person) is at position #\(i)")
  i += 1
}

三元条件表达式/Ternary Operator

The Ternary operator, ?: , should only be used when it increases clarity or code neatness. A single condition is usually all that should be evaluated. Evaluating multiple conditions is usually more understandable as an if statement or refactored into instance variables. In general, the best use of the ternary operator is during assignment of a variable and deciding which value to use.

仅当三元条件表达式能够让代码更清晰或者更整洁时才使用它。即使是单个条件分支也需要进行判断。而在存在多个条件分支时,利用 if 语句的方式或者将相关代码重构为实例变量的方式,能够降低整体的理解难度。总体而言,使用三元条件表达式的最佳场景,就是赋值变量并为变量选择值的时候。

推荐(Preferred):

let value = 5
result = value != 0 ? x : y

let isHorizontal = true
result = isHorizontal ? x : y

不推荐(Not Preferred):

result = a > b ? x = c > d ? c : d : y

Made with in Shangrao,China By 老雷

Copyright © devler.cn 1987 - Present

赣ICP备19009883号-1