Swift: an inout parameter will not be assigned if the assignment isn't instant
| Originator: | s | ||
| Number: | rdar://19085890 | Date Originated: | 26/11/2014 |
| Status: | Open | Resolved: | |
| Product: | Developer tools | Product Version: | |
| Classification: | Other bug | Reproducible: | Always |
Summary:
In swift, when defining an inout parameter to a function, the purpose is to directly access and modify that original variable. However, if the assignment isn't instant, in a case were you're waiting for a network request or such, the original variable will be left with it's original value.
Run the attached example project and read the line comments. I have provided two different scenarios, the first were the inout parameter works as expected, and the other were it doesn't.
Pseudo code explaining the problem:
var string: String?
func randomize(inout randomizedString: String?) {
randomizedString = "4" // guaranteed to be random
print(self.string) // prints 4
}
func asyncRandomize(inout randomizedString: String?) {
dispatch_after(seconds: 2) {
randomizedString = "4" // guaranteed to be random
print(self.string) // prints nil
}
}
randomize(&string)
string = nil // resetting it
asyncRandomize(&string)
Steps to Reproduce:
Run the attached project and see the comments and prints
Expected Results:
Both scenarios will set the &string, even after a async call
Actual Results:
The first scenario sets the variable, the second leaves it untouched
Version:
Xcode 6.1.1 6A2006
Notes:
A workaround is to use a closure instead, but that's not what I was looking for.
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!