Skip to content

Instantly share code, notes, and snippets.

@tempire
Last active December 1, 2020 06:18
Show Gist options
  • Star 20 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save tempire/dc6960cd610a012914a8 to your computer and use it in GitHub Desktop.
Save tempire/dc6960cd610a012914a8 to your computer and use it in GitHub Desktop.
swift array modification in loop
// FAILURE
var array = [["name": "glen"]]
for item in array {
item["rank"] = "advanced" // Generates an @lvalue error
}
// Even though array is immutable, it's of type <Array<Dictionary<String,String>>,
// item is assigned by let automatically.
// FAILURE
var array = [["name": "glen"]]
for (var item) in array {
item["rank"] = "advanced" // Compiles, but with unexpected results
}
// item is now mutable, but the assignment is only on item, not array,
// because array is of type <Array<Dictionary<String,String>>, which is copy by value,
// so array remains unchanged.
// If array was full of objects (like NSDictionary), it would work, because then it would be copy by
// reference
// SUCCESS
var array = [["name": "glen"]]
for index in 0..<array.count {
array[index]["rank"] = "advanced" // Expected behavior
}
// This works because we are modifying array directly, not a copy of it's value.
// SUCCESS
var array = [["name": "glen"]]
for index in 0..<array.count {
array[index]["rank"] = "advanced" // Expected behavior
}
// This works because we are modifying array directly, not a copy of it's value.
// SUCCESS
// You could also use the enumerate function which returns a tuple, for the same outcome
var array = [["name": "glen"]]
for (index, (var item)) = enumerate(array) {
array[index]["event_date"] = "advanced"
}
// Note the use of (var item). Using item would have the same problem as above, a copy of the value in array.
// It's interesting to note that (var item) is a mutable copy of the value returned in the tuple.
// If item was used by itself, it would be immutable, or equivalent to (let item)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment