1

I have a piece of code in SWIFT that I don't understand:

var peers: [String:NSSet] = [:]
for s in squares {
  var ps = reduce(units[s]!, NSMutableSet()) { set, u in
    set.addObjectsFromArray(u)
    return set
  }
  ps.removeObject(s)
  peers[s] = ps
}

squares is an array of String.

So far I have realized that peers probably is a key/value data structure with keys of String and values of NSSet. NSSet is similar to Array but it cannot accept duplicate items. The main part that I don't understand is actually the reduce function. Any explanation or instructive article/webpage is appreciated.

2 Answers 2

2

reduce is a method that's used to reduce an array into single value using the operator that you provide to construct the final result. Most demonstrations of this available in tutorials use + or * to reduce an array of numbers into a single sum or multiplication result.

The method you're using takes the input array units[s] and an initial value NSMutableSet() (an empty set), then applies the closure to each element in sequence.

Your code seems to indicate that the elements of units[s] are again arrays; so your data might look something like this:

units[s]: [
            [1, 2, 3, 4],
            [5, 6, 7, 8],
            [1, 3, 5, 7]
          ]

Making ps be:

ps: [ 1, 2, 3, 4, 5, 6, 7, 8 ]

after your reduce call.

Sign up to request clarification or add additional context in comments.

Comments

1
var ps = reduce(units[s]!, NSMutableSet()) { set, u in
    set.addObjectsFromArray(u)
    return set
  }

Reduce combines elements from array in the first parameter (units[s] should be an array) into second parameter (here NSMutableSet). The code in curly brackets that follows tells how to combine the elements. The "set" and "u" refer to the units[s] and the NSMutable set. So it takes each element in units[s] and adds them to the NSMutableSet.

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.