Add struct to array property using shorthand
I have an array of items
struct Item {
var id: String
}
How can I add all ids to an array using the reduce function ?
What I am trying:
self.items.reduce([String](), { $0.0.append($0.1.id)})
But compilation shows an error:
The contextual closure type '(_, [Item]) → _' expects 2 arguments, but 1 was used in the closure body
+3
source to share
3 answers
If you want to do it with shorthand, 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 problems:
- Shortening gives you 2 arguments, not one tuple with 2 values
- You cannot edit the argument passed to you in the block, you must return a new object
But in this case, the best solution is to use a map:
let reduceResult = items.map { $0.id }
+1
source to share