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

Swift类型错误:无法将Int赋值给Int?及姓名统计函数问题

解决你的Swift代码错误及优化建议

首先,咱们来拆解你遇到的核心问题,一步步搞定它:

1. 报错的根源:Reduce闭包返回值类型不匹配

你在b.reduce的闭包最后写了return newResult[arg.key] = counts,这行代码的问题在于:

  • Swift里字典的下标赋值操作newResult[arg.key] = counts,返回的是该键之前对应的旧值(类型为Int?),而不是你修改后的完整字典。
  • 但reduce的闭包要求返回的是[String: Int]类型(也就是累加器的类型),这就直接造成了类型不匹配,触发了Cannot assign value of type 'Int' to type 'Int?'的报错。

2. 修正后的可用代码

咱们把闭包的返回值改成修改后的newResult,同时保留你原本的计数逻辑,代码就能正常运行了:

func abbreviation(a:[String], b: [String : String]) ->[String : Int] {
    let dict = b.reduce([String : Int]()){ (result, arg) in
        var newResult = result
        let counts = a.reduce(0) { (newcount, value) -> Int in
            newcount + (value.components(separatedBy:arg.value).count - 1)
        }
        // 先完成赋值操作
        newResult[arg.key] = counts
        // 返回修改后的字典作为下一次累加的结果
        return newResult
    }
    return dict
}

// 测试调用
let dict = abbreviation(
    a:["This is chandan kumar and chandan kumar and new chandan","check chandan kumar","non ame"], 
    b:["first":"chandan","last":"kumar"]
)
print(dict) // 输出:["first": 4, "last": 3]

3. 额外优化:更可靠的计数方式

你原本用components(separatedBy:)的方式,在遇到连续重复的子串时可能会出错(比如"chandanchandan"会被误算成1次)。如果需要更精准的计数,推荐用正则表达式实现,适配所有场景:

import Foundation

func abbreviation(a:[String], b: [String : String]) ->[String : Int] {
    let dict = b.reduce([String : Int]()){ (result, arg) in
        var newResult = result
        let target = arg.value
        // 转义特殊字符,避免正则匹配出错
        guard let regex = try? NSRegularExpression(pattern: NSRegularExpression.escapedPattern(for: target)) else {
            newResult[arg.key] = 0
            return newResult
        }
        // 统计所有字符串中的匹配次数
        let counts = a.reduce(0) { totalCount, str in
            let range = NSRange(str.startIndex..., in: str)
            totalCount + regex.numberOfMatches(in: str, range: range)
        }
        newResult[arg.key] = counts
        return newResult
    }
    return dict
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 04:47:00