Reputation: 1084
I am trying to find out the count
of first and last name value exit in an array of a
and return a result as[String: Int]
a count with the same key.
I am getting error on this line newResult[arg.key] = counts
. Cannot assign value of type 'Int' to type '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
}
//result
let dict = abbreviation(a:["This is chandan kumar and chandan kumar and new chandan","check chandan kumar","non ame"], b:["first":"chandan","last":"kumar"])
Upvotes: 2
Views: 1856
Reputation: 271735
You are trying to return the result of an assignment expression:
return newResult[arg.key] = counts
or maybe you are trying to assign to the result of a return statement? This line doesn't make sense which way you look at it. You should separate the two things you are doing:
newResult[arg.key] = counts
return newResult
It seems like in this situation, you should use the other overload of the reduce
method - reduce(into:_:)
.
The reduce
method you are currently using requires you to return a new value every time, but you are just adding a KVP to a dictionary i.e. modifying an existing value. This means that you are creating lots of copies of dictionaries. This is a good sign that reduce(into:_:)
might be a better fit.
func abbreviation(a:[String], b: [String : String]) ->[String : Int] {
// notice the parameter label "into:"
let dict = b.reduce(into: [String : Int]()){ (result, arg) in
let counts = a.reduce(0) { (newcount, value) -> Int in
let count = newcount + (value.components(separatedBy:arg.value).count - 1)
return count
}
result[arg.key] = counts // with reduce(into:_:), you don't return anything, just modify the first argument
}
return dict
}
Upvotes: 1
Reputation: 47886
The error message is so confusing, and you may need to be accustomed to take it as Swift cannot infer some types in this context
.
With this line:
return newResult[arg.key] = counts
Do you know what is returned with this return
-statement? It's a Void
, also known as an empty tuple. (Void
is the result type of assignment statement in Swift.) You might have expected newResult
would be the result of the closure, but that sort of things would not happen unless you explicitly write return newResult
.
Try changing the line in to the following:
newResult[arg.key] = counts
return newResult
Upvotes: 1