スウィフト 3 / 4:
これは、UserDefaults を介してアクセスされる他の型の Optional-return 動作を模倣する Int/Double/Float/Bool キー値型の単純な拡張です。
( 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