Given an array of optional integers, I count the values which are not nil, up to (and including) a given index. I wrote the code down below. Is there another way to get the same result? A more Swift-friendly way?
Here is my code:
func getValuesCount(upTo index: Int, in values: [Int?]) -> Int {
return values[0 ... index].filter { value in return value != nil }.count
}
CodePudding user response:
One slightly more streamlined approach would be to use compactMap
instead of explicitly checking values for nil
. And prefix
can be used to get the first n values, even if the passed in index if larger than the array. And the return
is optional when there’s a one line result of the proper type.
func getValuesCount(upTo index: Int, in values: [Int?]) -> Int {
values.prefix(index).compactMap { $0 }.count
}
With the parameter name upTo
it implies that the range should be ..<index
instead of ...index
. So the use of prefix(index)
is similar to using ..<index
. If you want to include index
then you probably want prefix(index 1)
.