I don't like my following implementation of surroundingPositions to get the x- and y-Coordinates surrounding a specific position, because in my opinion it is too long for the simple intent and it has a pyramid of doom structure.
struct Position: CustomStringConvertible {
let x, y: Int
var surroundingPositions: [Position] {
var surroundingPositions: [Position] = []
for x in (self.x - 1)...(self.x + 1) {
for y in (self.y - 1)...(self.y + 1) {
if !(x == self.x && y == self.y) {
surroundingPositions.append(Position(x: x, y: y))
}
}
}
return surroundingPositions
}
var description: String {
return "(\(x),\(y))"
}
}
Usage:
let testPosition = Position(x: 1, y: 1)
print(testPosition.surroundingPositions)
// Output: [(0,0), (0,1), (0,2), (1,0), (1,2), (2,0), (2,1), (2,2)]
What is the shortest way to implement this with the same (correct) result? I'm thinking of functions like map, filter, reduce, etc., but can't find the right combination so far ...