【发布时间】:2021-02-17 10:54:26
【问题描述】:
我目前正在完成一项名为比较三元组 (https://www.hackerrank.com/challenges/compare-the-triplets/problem) 的黑客等级挑战,我只是想知道使用太多 IF 语句是否被认为是不好的编程习惯?除了使用 switch 语句之外,还有什么替代方法。请在下面查看我的代码解决方案:
import Foundation
func compareTriplets(a: [Int], b: [Int]) -> [Int] {
var compareArray = [0,0]
if a[0] == b[0]{
compareArray[0] = compareArray[0]
}
if a[0] < b[0]{
compareArray[0] = compareArray[0] + 1
}
if a[1] < b[1] {
compareArray[0] = compareArray[0] + 1
}
if a[2] < b[2] {
compareArray[0] = compareArray[0] + 1
}
if a[0] > b[0]{
compareArray[1] = compareArray[1] + 1
}
if a[1] > b[1] {
compareArray[1] = compareArray[1] + 1
}
if a[2] > b[2] {
compareArray[1] = compareArray[1] + 1
}
return compareArray
}
print(compareTriplets(a: [17,28,30], b: [99,28,8]))
【问题讨论】:
-
这会使代码更难阅读。您正在使用 if 而不是 if/else 这不合逻辑,因为 if a == b 例如,检查 a
标签: swift if-statement