斯威夫特 3 / 4:
这是 Int/Double/Float/Bool 键值类型的简单扩展,它模仿通过 UserDefaults 访问的其他类型的可选返回行为。
(2018 年 8 月 30 日编辑:根据 Leo 的建议更新了更有效的语法。)
extension UserDefaults {
/// Convenience method to wrap the built-in .integer(forKey:) method in an optional returning nil if the key doesn't exist.
func integerOptional(forKey: String) -> Int? {
return self.object(forKey: forKey) as? Int
}
/// Convenience method to wrap the built-in .double(forKey:) method in an optional returning nil if the key doesn't exist.
func doubleOptional(forKey: String) -> Double? {
return self.object(forKey: forKey) as? Double
}
/// Convenience method to wrap the built-in .float(forKey:) method in an optional returning nil if the key doesn't exist.
func floatOptional(forKey: String) -> Float? {
return self.object(forKey: forKey) as? Float
}
/// Convenience method to wrap the built-in .bool(forKey:) method in an optional returning nil if the key doesn't exist.
func boolOptional(forKey: String) -> Bool? {
return self.object(forKey: forKey) as? Bool
}
}
它们现在与其他内置的 get 方法(字符串、数据等)更加一致。只需使用 get 方法代替旧方法即可。
let AppDefaults = UserDefaults.standard
// assuming the key "Test" does not exist...
// old:
print(AppDefaults.integer(forKey: "Test")) // == 0
// new:
print(AppDefaults.integerOptional(forKey: "Test")) // == nil