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

KMM iOS端如何用Collator对含波兰语变音符号的列表排序?

KMM实现带波兰语变音符号的列表本地化排序

要解决KMM跨平台下带波兰语变音符号的字符串排序问题,通过expect/actual机制桥接各平台的本地化排序实现即可,具体步骤如下:

1. 在commonMain中定义跨平台接口

创建一个Kotlin文件(比如StringComparator.kt),在commonMain源集中定义expect函数,声明获取波兰语字符串比较器的接口:

expect fun polishStringComparator(): Comparator<String>

2. 在androidMain中实现Android端逻辑

利用Android平台的Collator类完成本地化比较:

import java.text.Collator
import java.util.Locale

actual fun polishStringComparator(): Comparator<String> {
    val polishCollator = Collator.getInstance(Locale("pl", "PL"))
    return Comparator { s1, s2 -> polishCollator.compare(s1, s2) }
}

3. 在iosMain中实现iOS端逻辑

通过Kotlin/Native调用iOS Foundation框架的NSString.localizedCompare方法,对应Swift中的本地化排序逻辑:

import platform.Foundation.NSString
import platform.Foundation.localizedCompare

actual fun polishStringComparator(): Comparator<String> {
    return Comparator { s1, s2 ->
        val nsStr1 = NSString.stringWithString(s1)
        val nsStr2 = NSString.stringWithString(s2)
        // 将NSComparisonResult转为Kotlin Int类型(负/零/正对应排序结果)
        nsStr1.localizedCompare(nsStr2).rawValue.toInt()
    }
}

4. 在commonMain中统一使用排序

在跨平台代码中直接调用定义好的比较器即可完成符合波兰语规则的排序:

val names = listOf("Zosia", "Łucja", "Asia")
val sortedNames = names.sortedWith(polishStringComparator())
// 输出结果:[Asia, Łucja, Zosia]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 13:45:32