我试图找出 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/