Swift 使用过多的IF语句是一个问题吗?敏捷的
我目前正在完成一个名为compare the triplets()的黑客等级挑战,我只是想知道使用太多if语句是否被认为是糟糕的编程实践?除了使用switch语句之外,还有什么其他选择。请参阅下面我的代码解决方案:Swift 使用过多的IF语句是一个问题吗?敏捷的,swift,if-statement,Swift,If Statement,我目前正在完成一个名为compare the triplets()的黑客等级挑战,我只是想知道使用太多if语句是否被认为是糟糕的编程实践?除了使用switch语句之外,还有什么其他选择。请参阅下面我的代码解决方案: import Foundation func compareTriplets(a: [Int], b: [Int]) -> [Int] { var compareArray = [0,0] if a[0] == b[0]{ comp
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]))
<代码>导入基础
func compareTriplets(a:[Int],b:[Int])->[Int]{
var compareArray=[0,0]
如果a[0]==b[0]{
compareArray[0]=compareArray[0]
}
如果a[0]b[0]{
compareArray[1]=compareArray[1]+1
}
如果a[1]>b[1]{
compareArray[1]=compareArray[1]+1
}
如果a[2]>b[2]{
compareArray[1]=compareArray[1]+1
}
回程舱
}
打印(比较文件(a:[17,28,30],b:[99,28,8]))
如果在发送的数组中有越来越多的元素,这将扩展很多 为什么不试试像这样的东西呢
func compareTriplets(a: [Int], b: [Int]) -> [Int] {
var compareArray = [0,0]
if a.count != b.count {
return compareArray
}
for index in 0..<(a.count) {
if a[index] > b[index] {
compareArray[0] += 1
}
else if a[index] < b[index] {
compareArray[1] += 1
}
}
return compareArray
}
func比较程序(a:[Int],b:[Int])->[Int]{
var compareArray=[0,0]
如果a.count!=b.count{
回程舱
}
对于0..b中的索引[索引]{
compareArray[0]+=1
}
如果a[index]
当然,如果数组长度可以不同,则可以取min或转到最小数组长度。这将使代码更难阅读。您使用的是if而不是if/else,这是不符合逻辑的,因为如果a==b,那么检查a是否