Skip to content

Instantly share code, notes, and snippets.

@AfricanSwift
Last active December 8, 2015 18:43
Show Gist options
  • Save AfricanSwift/be371fc4ad76cce79581 to your computer and use it in GitHub Desktop.
Save AfricanSwift/be371fc4ad76cce79581 to your computer and use it in GitHub Desktop.
Issues with index mutation in a loop
/*
Behaviour below is consistent with inline declaration,
index correctly mutates each interation
*/
for var index = 0; index < 10; index += 1 {
index += 2 //mutable index
print(index, terminator: " ") // output = 2 5 8 11
}
print("")
/*
Index appears to be a mutable (i.e. no warning),
but the outcome is unexpected.
Mutation is only applied at the beginning?
*/
for var index in 0 ..< 10 {
index += 2
print(index, terminator: " ") // output = 2 3 4 5 6 7 8 9 10 11
}
print("")
/*
This prior declaration of index is adopted by the c-style loop.
Again the behaviour is consistent with prior
declaration, index correctly mutates each interation
*/
var index: Int
for index = 0; index < 10; index += 1 {
/* mutable index */
index += 2
print(index, terminator: " ") // output = 2 5 8 11
}
print("")
/*
for in loop index variables completely ignores
the prior declaration of index 'var index: Int'.
*/
for index in 0 ..< 10 {
index += 2 //error 'index' is a 'let' constant ?? It was previous declared as: 'var index: Int'
print(index, terminator: " ")
}
/*
recreating this standard behavior of a c for loop
using a while loop construct is more complex, hence
struggling to see the value derived from eliminating
c style for loops.
*/
var idx = 0
let condition = {
() -> Bool in
defer {
if idx > 0 {
idx += 1
}
}
return idx < 10
}
while condition() {
idx += 2
print(idx, terminator: " ") // output = 2 5 8 11
}
print("")
/*
Evolution Concern:
These two evolution proposals will have a substantive impact on
mutability of indexes within of loop:
1. 0007-remove-c-style-for-loops
2. 0003-remove-var-parameters-patterns
Alternatives proposed:
The discussions on these evolution topics have typically centered around using a while loop,
but whatever the suggestion; index mutation is typically messy, see here for more examples:
https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20151207/001009.html
Closing Concerns:
1. I'm concerned that were both of these proposals to be implemented,
that we'd be left will an effectual solution for dealing with index
mutation in a loop.
2. The current behavior of the index declaration of "for in loop" is unexpected,
and can easily trip any newcomers (see examples above). It should either
respect the mutability of a prior declared variable, or restrict the reuse
of any previous declared variables in its index definition.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment