You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java的CustomComparator自定义比较器逻辑如何转换为Swift实现

Swift自定义比较器实现方案

1. 先修正数组初始化问题

你原有代码直接对空数组用下标赋值会触发越界崩溃,推荐改用append方式填充数组:

var items = [CustomItem]()
for i in 0..<offsets.count - 1 {
    items.append(CustomItem(start: offsets[i], end: offsets[i + 1]))
}
items.append(CustomItem(start: offsets[offsets.count - 1], end: output.size()))

2. 自定义排序逻辑实现

Swift的可变数组提供sort(by:)方法实现自定义排序,规则和Java的Comparator完全兼容:当闭包返回true时,第一个入参排在第二个入参前面,正好对应你Java比较器返回值小于0的场景,实现代码如下:

items.sort { custom1, custom2 in
    return CustomItem.compare_customs(content, custom1, custom2) < 0
}

逻辑说明

你已经实现的compare_customs静态方法返回值规则和Java一致:

  • 返回值 < 0:custom1 应该排在 custom2 前面
  • 返回值 = 0:两者顺序优先级相同
  • 返回值 > 0:custom2 应该排在 custom1 前面
    和sort(by:)的返回规则完全匹配,不需要调整原有比较逻辑即可直接复用。

内容的提问来源于stack exchange,提问作者hasan kaleli

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 17:15:00