swiftlang / swift

The Swift Programming Language
https://swift.org
Apache License 2.0
67.49k stars 10.35k forks source link

[SR-12505] #function on property declaration should map to the property name #54947

Open 05109ee7-7cd9-4cd4-92d0-698e676fc6af opened 4 years ago

05109ee7-7cd9-4cd4-92d0-698e676fc6af commented 4 years ago
Previous ID SR-12505
Radar rdar://problem/62201604
Original Reporter @an0
Type New Feature
Additional Detail from JIRA | | | |------------------|-----------------| |Votes | 1 | |Component/s | Compiler | |Labels | New Feature, PropertyWrappers | |Assignee | None | |Priority | Medium | md5: 5542778982789415575ba4d4c13348c4

Issue Description:

It'll be much more useful if #function on property declaration maps to the property name instead of the enclosing class name.

For example:

var defaults: [String: Any] = [:]

@propertyWrapper
struct UserDefaults<T> {

    let key: String
    let defaultValue: T

    init(key: String, defaultValue: T) {
        self.key = key
        self.defaultValue = defaultValue
    }

    var wrappedValue: T {
        get {
            defaults[key] as? T ?? defaultValue
        }
        set {
            defaults[key] = newValue
        }
    }

}

class Prefs: NSObject {
    // This doesn't work currently because `#function` gives you "Prefs" instead of "aPropertyWithAwesomeName".
    @UserDefaults(key: #function, defaultValue: 0) static var aPropertyWithAwesomeName: Int
    @UserDefaults(key: #function, defaultValue: 0) static var anotherPropertyWithAwesomeName: Int
}

print(Prefs.aPropertyWithAwesomeName)
print(Prefs.anotherPropertyWithAwesomeName)
Prefs.aPropertyWithAwesomeName = 1
print(Prefs.aPropertyWithAwesomeName)
// If it works it should print 0.
print(Prefs.anotherPropertyWithAwesomeName)
Prefs.anotherPropertyWithAwesomeName = 2
// If it works it should print 1.
print(Prefs.aPropertyWithAwesomeName)
print(Prefs.anotherPropertyWithAwesomeName)
beccadax commented 4 years ago

@swift-ci create