Home > other >  Replace value from multi-dimensional array
Replace value from multi-dimensional array

Time:10-07

I have an array made from a struct that holds multiple arrays and when trying to replace a value within the subarray I am met with an error:

Fatal error: Index out of range

  struct Main {
  var city: String
  var pop: Int
  var color: String
}

class Home {
    
var mainArray = [[Main]]()

func update() {
    let data = Main(city: "SF", pop: 2, color: "orange")
    mainArray.append(data)
    
    for var subArray in mainArray {
        for var i in subArray {
          var newCity = "SB"
          
           i.city = newCity
           subArray[0].city = i.city
       }

    }
  }
}

CodePudding user response:

Your code will never work because due to value semantics you are going to modify a copy of the array and subarray.

You have to modify always the original array directly, something like this

struct Main {
  var city: String
  var pop: Int
  var color: String
}

var mainArray = [[Main(city: "SF", pop: 1, color: "blue")], [Main(city: "NYC", pop: 2, color: "white")]]

for (index,  subArray) in mainArray.enumerated() {
    for (subIndex, _) in subArray.enumerated() {
        let newCity = "SB"
        mainArray[index][subIndex].city = newCity
    }
    
}
  • Related