我厌倦了在使用coolFeatureEnabled
时重复无数UserDefaults
字符串文字。如果有一个很好的方法来摆脱它们与Swift 3?
var coolFeatureEnabled: Bool {
get { return UserDefaults.standard.bool(forKey: "coolFeatureEnabled") }
set { UserDefaults.standard.set(newValue, forKey: "coolFeatureEnabled") }
}
答案 0 :(得分:1)
以下是如何在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) }
}
...