7

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

3 Answers 3

8

Try this:

items.reduce([String](), { res, item in
    var arr = res
    arr.append(item.id)
    return arr
})
Sign up to request clarification or add additional context in comments.

2 Comments

Error: Value of type '[Item]' has no member 'id'
Sorry, updated... As @vadian said though, you probably really want to use map.
5

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:

  1. Reduce is giving you 2 arguments, not single tuple with 2 values
  2. You can't edit argument that is passed to you in the block, you have to return new object

But in this case the best solution is to use map:

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

Comments

4

You probably mean map rather than reduce

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.