Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

[Hip, hip] ...(hip hip, array!) x2

I just learned this, which gives me the sum of an array:

func sumArray(array: [Int]) -> Int {
    return array.reduce(0, combine: +)
}

but next up, I have a multidimensional array that I want to sum... so I want a sum all of the values in the arrays within the parent array (ie: [[1, 2], [3, 4]] should equal 10). I'm trying:

parentArray.reduce(0, combine: .....)

but I'm getting stuck on how to unpack the child arrays. I've been researching how to work with closures, but it's super confusing given that I'm still pretty new to coding. I could also use a for loop and unpack the arrays that way, but I'm wondering if there is a better/cleaner way.

Any thoughts on how to do this?

3 Answers

Hi Leslie,

Try performing "flatmap" on the multidimensional array first (to "flatten" them into a single collection) and then reduce.

You can try this in Playgrounds to see:

let array = [[1, 2], [3, 4]]

let sum = array.flatMap{$0}.reduce(0, +)
print(sum)

Note that the above works for Swift 3. If you are using Swift 2, use ".reduce(0, combine:+)"

Thanks, that's awesome!

I also got the following for loop inside a for loop working, which isn't nearly as nice as the above answer:

var parentArray = [[Int]]() 
var total = 0

func sumParentArray() -> Int {   
     for x in 0 ..< parentArray.count {
            for y in 0 ..< parentArray[x].count {
            total += parentArray[x][y]
        }
    }
    return total
}

sumParentArray()

Though I don't quite understand why I had to use a range (x in 0..< parentArray.count) instead of just having it iterate over the arrays (x in parentArray).

I found a thorough explanation of Map Filter Reduce: http://useyourloaf.com/blog/swift-guide-to-map-filter-reduce/ for those who are curious.