Last active
July 18, 2018 02:45
-
-
Save takashi1975/e03cf335a82d6cc6c6fc3718ac66ed09 to your computer and use it in GitHub Desktop.
[Swift] Userdefaults+Extension (デフォルト値の考慮)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension UserDefaults { | |
//Get (デフォルト値あり) | |
internal static func get<T>(key: String, defaultValue: T) -> T { | |
let userdefaults = UserDefaults.standard | |
if userdefaults.object(forKey: key) != nil { | |
//Float | |
if (type(of: T.self) == type(of: Float.self)) { | |
let value = userdefaults.float(forKey: key) | |
return value as! T | |
} | |
//Double | |
if (type(of: T.self) == type(of: Double.self)) { | |
let value = userdefaults.double(forKey: key) | |
return value as! T | |
} | |
//Int | |
if (type(of: T.self) == type(of: Int.self)) { | |
let value = userdefaults.integer(forKey: key) | |
return value as! T | |
} | |
//Bool | |
if (type(of: T.self) == type(of: Bool.self)) { | |
let value = userdefaults.bool(forKey: key) | |
return value as! T | |
} | |
//String | |
if (type(of: T.self) == type(of: String.self)) { | |
let value = userdefaults.string(forKey: key) | |
return value as! T | |
} | |
} | |
return defaultValue | |
} | |
//Get (デフォルト値なし) | |
internal static func get<T>(key: String) -> T? { | |
let userdefaults = UserDefaults.standard | |
//Logger.log(message: String("Setting.get T.type: \(type(of: T.self))")) | |
if UserDefaults.standard.object(forKey: key) != nil { | |
//Float | |
if (type(of: T.self) == type(of: Float.self)) { | |
let value = userdefaults.float(forKey: key) | |
return value as? T | |
} | |
//Double | |
if (type(of: T.self) == type(of: Double.self)) { | |
let value = userdefaults.double(forKey: key) | |
return value as? T | |
} | |
//Int | |
if (type(of: T.self) == type(of: Int.self)) { | |
let value = userdefaults.integer(forKey: key) | |
return value as? T | |
} | |
//Bool | |
if (type(of: T.self) == type(of: Bool.self)) { | |
let value = userdefaults.bool(forKey: key) | |
return value as? T | |
} | |
//String | |
if (type(of: T.self) == type(of: String.self)) { | |
let value = userdefaults.string(forKey: key) | |
return value as? T | |
} | |
} | |
return nil | |
} | |
//Set | |
internal static func set<T>(key: String, value: T) { | |
let userdefaults = UserDefaults.standard | |
userdefaults.set(value, forKey: key) | |
} | |
//Remove | |
internal static func remove(key: String) { | |
let userdefaults = UserDefaults.standard | |
if (userdefaults.object(forKey: key) != nil) { | |
userdefaults.removeObject(forKey: key) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment