There are obviously many ways, one way (which doesn't create an intermediate array, or require row
to be sorted) is with reduce
:
row.reduce(nil as Int?) { minSoFar, this in
guard this != 0 else { return minSoFar }
guard let minSoFar = minSoFar else { return this }
return min(minSoFar, this)
}
Which is equivalent to, but more readable than, the shorter:
row.reduce(nil as Int?) { $1 != 0 ? min($0 ?? $1, $1) : $0 }
The result is optional, since there might not be any non-zero elements.
edit: The min(by:)
solution could also indeed be used, but it is also somewhat unreadable and returns 0
in case there are no non-zero elements (instead of nil
):
row.min { $0 == 0 ? false : ($1 == 0 ? true : $0 < $1) }