Strange Behaviour in Swift: constant defined with LET but behaving like a variable defined with VAR
- by Sam
Stuck on the below for a day! Any insight would be greatly appreciated. The constant in the first block match0 behaves as expected. The constant defined in the second block does not behave as nicely in the face of a change to its "source":
var str = "+y+z*1.0*sum(A1:A3)"
if let range0 = str.rangeOfString("^\\+|^\\-|^\\*|^\\/", options: NSStringCompareOptions.RegularExpressionSearch){
let match0 = str[range0]
println(match0) //yields "+" - as expexted
str.removeRange(range0)
println(match0) //yields "+" - as expected
str.removeRange(range0)
println(match0) //yields "+" - as expected
}
if let range1 = str.rangeOfString("^\\+|^\\-|^\\*|^\\/", options: NSStringCompareOptions.RegularExpressionSearch){
let match1 = str[range1]
println(match1) //yields "+" as expected
str.removeRange(range1)
println(match1) //!@#$ OMG!!!!!!!!!!! a constant variable has changed! This prints "z"
}
The following are the options I can see:
match1 has somehow obtained a reference to its source instead of being copied by value [Problem: Strings are value types in Swift]
match1 has somehow obtained a closure to its source instead of just being a normal constant/variable? [Problem: sounds like science fiction & then why does match0 behave so well?]
Could there be a bug in the Swift compiler? [Problem: Experience has taught me that this is very very very rarely the solution to your problem...but it is still in beta]