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

Swift中min函数未返回预期最短字符串问题求助

为什么Swift中min函数无法正确获取最短字符串?

在Xcode Playground中尝试获取字符串的最长前缀子串时,发现一个问题:通过比较字符数量的方式能正确得到最短字符串"swim",但使用min函数却得到了"swill",以下是具体代码和原因分析:

完整代码

var string = "swimftch swim swimftc swill"

let splitArray = string.split(separator: " ")

var shortestString = string
for singleString in splitArray {
    
    // 此方式正常工作,得到预期的"swim"
//    if shortestString.count > singleString.count {
//        shortestString = String(singleString)
//    }
    
    // 此方式无法得到预期结果,返回"swill"
    shortestString = min(String(singleString), shortestString)
    print(shortestString)
}

var isPrefixed = false

func checkSubString() {
    for sub in splitArray {
        if sub.contains(shortestString) {
            print(shortestString)
            isPrefixed = true
        } else {
            isPrefixed = false
        }
    }
    if !isPrefixed {
        shortestString.popLast()
        checkSubString()
    } else {
        print(shortestString)
    }
}


checkSubString()

关键代码片段

for singleString in splitArray {
    
    // 此方式正常工作,得到预期的"swim"
//    if shortestString.count > singleString.count {
//        shortestString = String(singleString)
//    }
    
    // 此方式无法得到预期结果,返回"swill"
    shortestString = min(String(singleString), shortestString)
    print(shortestString)
}

原因解释

Swift中min函数对String类型的比较逻辑是字典序比较,而非按字符串长度比较:

  • 字典序比较会逐个字符对比ASCII值,直到找到第一个不同的字符:比如"swill"和"swim",前三个字符s、w、i完全相同,第四个字符l的ASCII值(108)小于m的ASCII值(109),因此min("swill", "swim")会返回"swill"。
  • 你的循环执行过程:
    1. 初始shortestString是原长字符串"swimftch swim swimftc swill",第一次和"swimftch"比较,字典序更小的"swimftch"成为新的shortestString;
    2. 第二次和"swim"比较,"swim"字典序更小,更新为"swim";
    3. 第三次和"swimftc"比较,"swim"依然字典序更小,保持不变;
    4. 第四次和"swill"比较,由于"swill"的第四个字符l比"swim"的m小,字典序更靠前,所以shortestString被更新为"swill"。

而通过count比较的方式是直接对比字符串的长度,"swim"的长度为4,是所有分割后字符串中最短的,因此能正确得到预期结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 10:32:40