Swift for-in loop scope for array values doesn't match documentation in The Swift Programming Language book.
| Originator: | mledford | ||
| Number: | rdar://18114466 | Date Originated: | 24-Aug-2014 04:24 PM |
| Status: | Open | Resolved: | |
| Product: | Developer Tools | Product Version: | Xcode 6.0b6 |
| Classification: | Other Bug | Reproducible: | Always |
Summary:
In The Swift Programming Language book it states:
“NOTE
The index constant exists only within the scope of the loop. If you want to check the value of index after the loop completes, or if you want to work with its value as a variable rather than a constant, you must declare it yourself before its use in the loop.”
Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks. https://itun.es/us/jEUH0.l
However, when I declare a var before its use in the loop the value is not as expected once the loop has exited.
Steps to Reproduce:
1. Run the following code.
let a = [1,2,3,4]
let valueToFind = 2
var value: Int?
for value in a {
if value == valueToFind {
break
}
}
if value != valueToFind {
println("This is supposed to be \(valueToFind) according to the Swift book but instead it's \(value). Sad panda.")
} else {
println("Hooray! \(value) is the right value according to the Swift book. Happy Panda!")
}
2) Inspect the output and see if you have a happy panda or a sad panda.
3) There is no step three.
Expected Results:
I expected the output would show a happy panda.
Actual Results:
I get a message about a sad panda. :(
Version:
Version 6.0b6 (6A280e)
Notes:
I'm not sure if the implementation is incorrect or the documentation is incorrect so I'll leave it up to you to decide which it should be. :)
Configuration:
OS X 10.9.4 (13E28)
Attachments:
Comments
Please note: Reports posted here will not necessarily be seen by Apple. All problems should be submitted at bugreport.apple.com before they are posted here. Please only post information for Radars that you have filed yourself, and please do not include Apple confidential information in your posts. Thank you!
Interesting find but consistent with documentation, I think...
Well, it sort of makes sense, that it doesn't worked, since the index is implicitly (re)declared as a constant, which only exists in context of the loop. I think what they meant was something along the lines of this: ... let valueToFind = 2 var exit: Int?
for value in a { if value == valueToFind { exit = value break } } ....