I'm working in swift and I've got a custom class Array2D
to handle fixed-width, two-dimensional arrays of integers. What I'm trying to do is write a simple, ideally-elegant function max() -> Int?
to behave the same way as for a 1-D array: return nil
if the array is empty, or else the maximum value in the array. I make no promises about the array contents being positive.
For the sake of simplicity, I'm writing these functions as freestanding rather than parts of a class here.
Broadly speaking, I'm trying to do this:
func max(array: [[Int]]) -> Int? {
set up a variable for maximum value maxSoFar
for row in array {
if row.max() > maxSoFar { maxSoFar = row.max() }
}
return maxSoFar
}
What I'm struggling with is avoiding lots of nested optional handling: I have to handle the Int?
returned by max
for each row of the array, and it looks like I'll need maxSoFar
to be an Int?
as well, since I don't want to initialize it to zero since all the entries in the array could be negative.
So, a few options:
func max1(array: [[Int]]) -> Int? {
if array.count == 0 || array[0].count == 0 { return nil }
var maxval: Int = array[0][0]
for row in array {
if let rowmax = row.max() {
if rowmax > maxval { maxval = rowmax }
}
}
return maxval
}
func max2(array: [[Int]]) -> Int? {
var maxval: Int?
for row in array {
guard let rowmax = row.max() else {
return nil
}
guard let temp = maxval else {
maxval = rowmax
continue
}
if rowmax > temp {
maxval = rowmax
}
}
return maxval
Thoughts? Alternatives? I'd be delighted to learn a better way to handle this.