gpt4 book ai didi

swift - 使用谓词自定义排序顺序

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

我有一个数组

arr = ["A", "B", "a", "b", "1", "2"]

当我排序时使用:

arr.sorted(by: <)

我得到:

["1", "2", "A", "B", "a", "b"]

但我正在寻找结果:

["a", "b", "A", "B", "1", 2"]

一种自定义排序顺序,其中小号按排序顺序排在第一位,然后按排序顺序加盖,最后按排序顺序排列数字。有什么简单的方法可以做到这一点?

最佳答案

我可能是错的,但我认为您需要实现自己的自定义排序方法:

var arr = ["A", "B", "a", "b", "1", "2"]
arr.sort {
if $0.first?.isLowercase == true && ($1.first?.isUppercase == true || $1.first?.isWholeNumber == true) {
return true
}
if $0.first?.isUppercase == true && $1.first?.isWholeNumber == true {
return true
}
if $0.first?.isWholeNumber == true && ($1.first?.isLowercase == true || $1.first?.isUppercase == true) {
return false
}
return $0 < $1
}

print(arr) // "["a", "b", "A", "B", "1", "2"]\n"

extension MutableCollection where Element: StringProtocol, Self: RandomAccessCollection {
mutating func customSort(by areInIncreasingOrder: (Element, Element) throws -> Bool = (<)) rethrows {
try sort {
if try areInIncreasingOrder("1","2") {
if $0.first?.isLowercase == true && ($1.first?.isUppercase == true || $1.first?.isWholeNumber == true) {
return true
}
if $0.first?.isUppercase == true && $1.first?.isWholeNumber == true {
return true
}
if $0.first?.isWholeNumber == true && ($1.first?.isLowercase == true || $1.first?.isUppercase == true) {
return false
}
} else {
if $0.first?.isWholeNumber == true && ($1.first?.isLowercase == true || $1.first?.isUppercase == true) {
return true
}
if $0.first?.isUppercase == true && ($1.first?.isLowercase == true || $1.first?.isWholeNumber == true) {
return true
}
if $0.first?.isLowercase == true && ($1.first?.isUppercase == true || $1.first?.isWholeNumber == true) {
return false
}
}
return try areInIncreasingOrder($0,$1)
}
}
}

var array =  ["B","A","b", "a", "1", "2"]
do {
try array.customSort()
print(array) // "["a", "b", "A", "B", "1", "2"]\n"
} catch {
print(error)
}

关于swift - 使用谓词自定义排序顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58512665/

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