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


Try the following:



items.reduce([String](), { res, item in
    var arr = res
    arr.append(item.id)
    return arr
})

      

+1


source


You probably mean map

, notreduce

let ids = items.map{ $0.id }

      

+1


source







All Articles