I have an array of Items
struct Item {
var id: String
}
How can I append all the ids to an array using reduce function?
What I try:
self.items.reduce([String](), { $0.0.append($0.1.id)})
But compiler shows an error:
Contextual closure type '(_, [Item]) -> _' expects 2 arguments, but 1 was used in closure body
The reduce() method executes the function for each value of the array (non-empty array) from left to right. The reduce() method has the following syntax: let arr = [];arr. reduce(callback(acc, curVal, index, src), initVal);
reduce() method in JavaScript is used to reduce the array to a single value and executes a provided function for each value of the array (from left-to-right) and the return value of the function is stored in an accumulator. Syntax: array.reduce( function(total, currentValue, currentIndex, arr), initialValue )
You can reduce an array into a new array. For instance, lets reduce an array of amounts into another array where every amount is doubled. To do this we need to set the initial value for our accumulator to an empty array. The initial value is the value of the total parameter when the reduction starts.
reduce() method is a bit more flexible. It can return anything. Its purpose is to take an array and condense its content into a single value. That value can be a number, a string, or even an object or new array.
Try this:
items.reduce([String](), { res, item in
var arr = res
arr.append(item.id)
return arr
})
If you want to do it with reduce, here is a snippet for Swift 3 and 4:
struct Item {
var id: String
}
var items = [Item(id: "text1"), Item(id: "text2")]
let reduceResult = items.reduce([String](), { $0 + [$1.id] } )
reduceResult // ["text1", "text2"]
There were 2 issues:
But in this case the best solution is to use map:
let reduceResult = items.map { $0.id }
You probably mean map
rather than reduce
let ids = items.map{ $0.id }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With