syedfa syedfa - 1 month ago 9
iOS Question

Trying to append text to a property inside a loop in Swift

Dear fellow iOS/Swift developers:

I have an array of struct objects. These objects have a property for title (which is a String), and a property for location (of type Location).

What I would like to is append a double value for distance derived from the location property and the distance function with another, existing Location object, to the title property. Here is the code I am working with:

self.myList.map({$0.title.append("\($0.location.distance(from: location!)/1000)")})


The problem here is that the map function returns a new array, however, I need to make the change to the existing array, since I'm using this array as the datasource for my UITableView. The other problem is that despite me making the title property a var, I am always told the following error message:

Cannot use mutating member on immutable value: '$0' is immutable.


Can anyone figure out how to do this?

Thanks in advance to all who reply.

Answer Source

You should iterate over the array like this:

for (i, _) in myList.enumerated() {
    myList[i].title.append("\(myList[i].location.distance(from: location) / 1000)")
}