简体   繁体   中英

Mapping Structs in Swift

I have an array of a custom struct that has a INT variable that I would like to get the sum of conditionally based on another variable of the struct. Here is example of what the code looks like:

struct Point {
    var amount: Int
    var add: Bool
}

let arr = [Point(amount: 9, add: false), Point(amount: 9, add: true), Point(amount: 9, add: true)]

let sum:Int = arr.compactMap({ point in
    return point.add ? point.amount : 0
}) 

print(sum)

But I am getting this error: error: cannot convert value of type '[Int]' to specified type 'Int'

Isn't compact map supposed to reduce the array down to a certain type? How can I accomplish what I am trying to do?

You are looking for reduce , not compactMap . reduce takes an array and transforms it to a single value.

What you're looking for could done like this:

let sum: Int = arr.reduce(0, { acc, point in
    acc + (point.add ? point.amount : 0)
})

Or, turned into a one-liner:

let sum:Int = arr.filter(\.add).map(\.amount).reduce(0, +)

The second solution is not particularly efficient -- not suitable for larger collections, but perfectly reasonable for your example. Unless things have changed, even the first solution won't win any speed tests against a simple for loop. But, again, unless you have huge collections you're working with, it's perfectly reasonable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM