luk2302 luk2302 - 6 months ago 9
Swift Question

Ensure that two dimensional array is rectangular

I am struggling to find a neat way of ensuring (via

guard
) that some input is an correctly sized rectangular array.

I have a data structure that already has two fields
width
and
height
. The input comes in form of a
String
representation of a
JSON
which is then parsed to be an
[[Int]]
which then has to be checked to have the correct dimensions. For simplicity sake the JSON-parsing is ignored here and lets assume the actual JSON was not malformed.

enum Exception : ErrorType {
case InvalidJson
}

class Test {
var width = 3
var height = 2

func someFunction(array:[[Int]]) throws {
// checking
}
}

let test = Test()
do {
try test.someFunction([[1,2],[1,2],[1,2]]) // success
try test.someFunction([[1,2],[1,2,3],[1]]) // fail
} catch let exception {
print(exception)
}


What I currently got working is the following version of
someFunction
:

func someFunction(array:[[Int]]) throws {
guard array.count == self.width else {
throw Exception.InvalidJson
}
// guard the array[index].count
}


Obviously guarding the
array.count
is no problem - the problem is checking the count of the nested arrays.

Is there a way of writing one neat guard statement or is there eventually even a builtin?

I thought about something along the lines of

array.map({ $0.count }).onlyContains(self.height)


to ensure that all sub-arrays are of the length
self.height
.


How can I ensure that a 2-dimensional array is rectangular of a specific size?

Answer

What I currently got working is the following version of someFunction:

func someFunction(array:[[Int]]) throws {
    guard array.count == self.width else {
        throw Exception.InvalidJson
    }
    guard array.filter({$0.count != self.height}) == [] else {
        throw Exception.InvalidJson
    }
    print("correct input")
}

It filters out the arrays in array that have a length different than self.height. I then checks that the resulting array is empty (== [] or .count == 0).

Not certain if that covers all use cases.

Comments