gpt4 book ai didi

arrays - 对排除 Nil 的数组进行排序

转载 作者:行者123 更新时间:2023-11-28 09:43:54 25 4
gpt4 key购买 nike

我正在尝试对包含零变量的数组进行排序。

class TestArray {
var a: String? = nil
var b: String? = nil
init(a: String?, b: String?) {
self.a = a
self.b = b
}
}

let first = TestArray(a: "xxx", b: "yyy")
let second = TestArray(a: "zzz", b: "zzz")
let third = TestArray(a: "aaa", b: nil)

var array = [first, second, third]
array.sort(by: {($0.a as String!) > ($1.a as String!)})

array.sort(by: {($0.b as String!) > ($1.b as String!)}) // Throws an error

如何按 b 排序并在数组末尾留下 b = nil 的第三个 TestArray?此外,我想对所有 b 进行排序,然后对 b = nil 的数组按 a 对剩余的进行排序。

最佳答案

我相信这应该涵盖您想要的情况,而无需多次迭代(这是昂贵的)

array.sort { (lessThan, item) -> Bool in

switch (lessThan.a, lessThan.b, item.a, item.b) {
// if bs exist, use that comparison
case (_, .some(let lessThanB), _, .some(let itemB)):
return lessThanB < itemB
// if bs don't exist by as do, use that comparison
case (.some(let lessThanA), .none, .some(let itemA), .none):
return lessThanA < itemA
// if one item has a value but the other doesn't, the item with the value should be first
case (_, .some(_), _, .none), (.some(_), _, .none, _ ):
return true

default:
return false
}
}

关于arrays - 对排除 Nil 的数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40140401/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com