0

I have a 2-dimensional 5x5 array in Swift. I am trying to have each array item to present a struct that has properties like cost and heuristics. for example, the grid[0][0] item should have cost and heuristics values.

Swift implementation:

struct Spot {
    var cost: Int  // cost
    var heu: Int  // heuristics
}

var grid = [[Int]]

In Javascript I used to do it as:

function Spot() {
  this.cost = 0;
  this.heu = 0;
}

//This is what I'm looking for something equivalent in Swift
grid[0][0] = new Spot();

Sorry if this seems very basic, but I'm a beginner in Swift.

1
  • Depending on what exactly Spot is (its name, and the names of its members don't really communicate much), you probably want an [[Int?]], with nils marking the empty spots, rather than Spot instances with 0 cost and 0 "heu" Commented Jul 6, 2019 at 1:45

1 Answer 1

3

You need an array of Spot arrays [[Spot]], not an array of Int arrays [[Int]].

struct Spot {
    let cost: Int  // cost
    let heu: Int  // heuristics
}

var grid: [[Spot]] = .init(repeating: .init(repeating: .init(cost: 0, heu: 0), count: 5), count: 5)

grid[0][0] = .init(cost: 10, heu: 5)

print(grid)  // "[[Spot(cost: 10, heu: 5),...
print(grid[0][0].cost)   // 10
print(grid[0][0].heu)    // 5
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.