Swift should require "mutating" on object methods that change state
| Originator: | brent | ||
| Number: | rdar://17285019 | Date Originated: | 12-Jun-2014 04:10 AM |
| Status: | Duplicate/17279012 | Resolved: | |
| Product: | Developer Tools | Product Version: | Xcode6-Beta (6A215l) |
| Classification: | Feature (New) | Reproducible: | Always |
Summary:
In a world where we’re encouraged to do everything on a GCD queue, the easiest way to make code thread-safe is to ensure only one thread mutates a given object at a time. As a first step, it might be good to require methods to declare that they mutate state. Writing a method that did not do so, but did call “mutating” methods on self or self’s properties, would be an error. Property setters would be considered implicitly “mutating”.
Steps to Reproduce:
1. Write a Swift class like:
class Foo {
var x: Int = 1
func increment() { x++ }
}
2. Compile.
Expected Results:
An error is shown, instructing the user to label the Foo.increment method “mutating”.
Actual Results:
No such error is shown for a class (as opposed to a struct).
Notes:
Currently, this would only be an advisory annotation for developers; perhaps a future version of the static analyzer could notice dubious constructs like calling mutable methods on an object that has been captured by a closure passed to dispatch_async(), or a future version of Swift could allow developers to explicitly state that a variable’s object should not be mutated.
Since Objective-C has no analogous feature (yet), some methods would be accessible from Swift that were mutating but did not mark themselves as such. However, if property setters were implicitly “mutating”, developers would still see some benefit from this feature when working with Objective-C frameworks.
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!