Created
June 29, 2020 16:18
-
-
Save revblaze/2bab81705328aa63965d73fce41534fe to your computer and use it in GitHub Desktop.
Quick and easy UserDefaults
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
let Defaults = UserDefaults.standard | |
struct Settings { | |
static let firstLaunch = Defaults.bool(forKey: Keys.firstLaunch) | |
static let totalLaunches = Defaults.integer(forKey: Keys.totalLaunches) | |
} | |
struct Keys { | |
static let firstLaunch = "FirstLaunchKey" | |
static let totalLaunches = "TotalLaunchesKey" | |
/** | |
Saves allowable UserDefault values to a specified key | |
- Parameters: | |
- value: The value to be saved | |
- forKey: The key-value of the object to be saved | |
# Usage: | |
Keys.saveToDefaults(true, forKey: Keys.firstLaunch) | |
Keys.saveToDefaults(1, forKey: Keys.totalLaunches) | |
*/ | |
static func saveToDefaults(_ value: Any, forKey: String) { | |
if allowedType(value) { | |
print("Setting Default: \(value), forKey: \(forKey)") | |
Defaults.set(value, forKey: forKey) | |
} else { | |
print("Error: invalid Default type\nUnable to set Default: \(value), forKey: \(forKey)") | |
} | |
} | |
// Allowable types to be saved to UserDefaults | |
static func allowedType(_ object: Any) -> Bool { | |
switch object { | |
case is Bool: return true | |
case is String: return true | |
case is URL: return true | |
case is Int: return true | |
case is Double: return true | |
case is Float: return true | |
default: return false | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment