在Swift中,我有两个从最大到最小排序的数组,这意味着数组的值是Comparable
。我想定义一种比较两个数组的自定义方式来表示一个“小于”另一个。一个数组较少的数组总是小于一个较大的数组。我提出的工作很好,但运营商似乎太笨重。它只是觉得应该有一些方法来压缩它,或者有一个内置函数或者内置函数的组合,以实现我想要的功能。这是我有什么:有没有更好的方法来比较两个排序的数组?
func <<T where T: Comparable>(lhs: [T], rhs: [T]) -> Bool {
if lhs.count < rhs.count {
return true
}
for i in 0..<lhs.count {
if lhs[i] > rhs[i] {
return false
}
}
return true
}
let first = [9, 8, 7, 6, 4]
let second = [9, 8, 7, 6, 5]
let third = [8, 7, 6, 5, 4]
let fourth = [9, 8, 7, 6]
let firstSecondComp: Bool = first < second // true
let secondFirstComp: Bool = second < first // false
let secondThirdComp: Bool = second < third // false
let thirdSecondComp: Bool = third < second // true
let firstThirdComp: Bool = first < third // false
let thirdFirstComp: Bool = third < first // true
let fourthFirstComp: Bool = fourth < first // true
let fourthSecondComp: Bool = fourth < second // true
let fourthThirdComp: Bool = fourth < third // true
任何方式来改善比较功能的主体?
编辑
固定崩溃所指出的狮子座Dabus和包括马丁的r答案:
func <<T where T: Comparable>(lhs: [T], rhs: [T]) -> Bool {
if lhs.count < rhs.count {
return true
}
else if lhs.count > rhs.count {
return false
}
return !zip(lhs, rhs).contains { $0 > $1 }
}
请注意,如果你的第一个数组有多个元素,比第二'lhs.count> rhs.count“会使你的应用崩溃 –
好的观察!完全滑过我。 –