如何使用 Swift 3 摆脱 `UserDefaults` 中的 `forKey` 字符串文字?
How to get rid of `forKey` string literals in `UserDefaults` with Swift 3?
我厌倦了在使用 UserDefaults
时重复无数 coolFeatureEnabled
字符串文字。如果有摆脱它们的好方法 Swift 3?
var coolFeatureEnabled: Bool {
get { return UserDefaults.standard.bool(forKey: "coolFeatureEnabled") }
set { UserDefaults.standard.set(newValue, forKey: "coolFeatureEnabled") }
}
下面是如何在 Swift 3
中使用 #function
避免字符串文字
// a little bit of setup
private func getBool(key: String = #function) -> Bool {
return UserDefaults.standard.bool(forKey: key)
}
private func setBool(_ newValue: Bool, key: String = #function) {
UserDefaults.standard.set(newValue, forKey: key)
}
// and here is the fun part
var coolFeatureEnabled: Bool {
get { return getBool() }
set { setBool(newValue) }
}
var anotherFeatureEnabled: Bool {
get { return getBool() }
set { setBool(newValue) }
}
...
我厌倦了在使用 UserDefaults
时重复无数 coolFeatureEnabled
字符串文字。如果有摆脱它们的好方法 Swift 3?
var coolFeatureEnabled: Bool {
get { return UserDefaults.standard.bool(forKey: "coolFeatureEnabled") }
set { UserDefaults.standard.set(newValue, forKey: "coolFeatureEnabled") }
}
下面是如何在 Swift 3
中使用#function
避免字符串文字
// a little bit of setup
private func getBool(key: String = #function) -> Bool {
return UserDefaults.standard.bool(forKey: key)
}
private func setBool(_ newValue: Bool, key: String = #function) {
UserDefaults.standard.set(newValue, forKey: key)
}
// and here is the fun part
var coolFeatureEnabled: Bool {
get { return getBool() }
set { setBool(newValue) }
}
var anotherFeatureEnabled: Bool {
get { return getBool() }
set { setBool(newValue) }
}
...