gpt4 book ai didi

swift 3 : sorting arrays with sort function: seeing error of Ambiguous use of 'sort(comparator:)'

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

此代码生成此错误:

Ambiguous use of 'sort(comparator:)'

chars.sort {
let s0 = $0 as? String
let s1 = $1 as? String
if array.index(of: s0) == array.index(of: s1) {
ComparisonResult.orderedSame
} else if array.index(of: s0) < array.index(of: s1) {
ComparisonResult.orderedDescending
} else {
ComparisonResult.orderedAscending
}
}

其他 SO 帖子建议将 sort 函数的参数转换为字符串,但错误仍然存​​在。谁能解释一下为什么?

最佳答案

如果你有这样的数组

let chars: [Any] = ["g", "c", "a"]

并且您想使用元素到另一个数组中的顺序对其进行排序

let orders = ["a", "b", "c", "e", "f"]

你可以简单地写

let sorted = chars
.flatMap { $0 as? String }
.sorted { orders.index(of:$0) ?? Int.max < orders.index(of: $1) ?? Int.max }

// print(sorted)
// ["a", "c", "g"]

关于 swift 3 : sorting arrays with sort function: seeing error of Ambiguous use of 'sort(comparator:)' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39674505/

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