Skip to content

Instantly share code, notes, and snippets.

@m760622
Forked from tempire/array_modification.swift
Created July 11, 2018 02:52
Show Gist options
  • Save m760622/898c2de598c24f1ecf49941bb85dc57f to your computer and use it in GitHub Desktop.
Save m760622/898c2de598c24f1ecf49941bb85dc57f 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