Since you are only looking for neighboring positions and apparently do not have restrictions on x or y , you can save an array of translations (x, y) , each of which maps this Position one of its 8 neighboring ones.
struct Position: CustomStringConvertible { let x, y: Int // order of resulting neighbouring positions, given a position P // (1) (2) (3) // (4) (P) (5) // (6) (7) (8) private static let surroundingPositionsTranslations: [(x: Int, y: Int)] = [ (-1, -1), (0, -1), (1, -1), (-1, 0), (1, 0), (-1, -1), (0, -1), (1, -1)] var surroundingPositions: [Position] { return Position.surroundingPositionsTranslations .map { Position(x: x + $0.x, y: y + $0.y) } } var description: String { return "(\(x),\(y))" } } // Note that I've changed the order wrt OP:s original code // (modify the transfotmation above to modify the order) let testPosition = Position(x: 1, y: 1) print(testPosition.surroundingPositions) // Output: [(0,0), (1,0), (2,0), (0,1), (2,1), (0,0), (1,0), (2,0)]
dfri source share