swift - 无法将类型 'Int' 的值分配给类型 'Int?'

标签 swift

我试图找出 a 数组中名字和姓氏值的 count 并将结果返回为 [String: Int] 具有相同键的计数。

我在这一行遇到错误 newResult[arg.key] = counts无法将“Int”类型的值分配给“Int”类型?

  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
                let count = newcount + (value.components(separatedBy:arg.value).count - 1)
                return count
            }
            return newResult[arg.key] = counts
        }
        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"])

最佳答案

错误消息非常令人困惑,您可能需要习惯于接受它,因为 Swift 无法推断此上下文中的某些类型

用这一行:

return newResult[arg.key] = counts

你知道这个return语句返回了什么吗?它是一个 Void,也称为空元组。 (Void 是 Swift 中赋值语句的结果类型。)您可能期望 newResult 将是闭包的结果,但这种情况不会发生,除非您显式写入return newResult

尝试将行更改为以下内容:

newResult[arg.key] = counts
return newResult

关于swift - 无法将类型 'Int' 的值分配给类型 'Int?',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55429007/

相关文章:

macos - 使用 Realm 高效实现查找或创建

swift - 通过滑动从 UIViewController 中放松

swift - Sprite 节点的起始位置

ios - Swift - 在 UIPageViewController 中的 3 个不同 View Controller 之间导航按钮

ios - Alamofire 的响应不正确?

swift - 我如何知道在 Swift 中使用哪种方式转换对象?

swift - 按钮不起作用

ios - 向 iOS 项目添加和访问二进制 blob 原始数据文件

ios - Swift:如何拆分字符串然后提取特定的子字符串?

swift - 如何调整或删除标签以使 NSView 重绘成为可能?