Skip to content

Instantly share code, notes, and snippets.

@kayoslab
Created July 8, 2020 08:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kayoslab/66f5952959781f3a028aead540e5cc69 to your computer and use it in GitHub Desktop.
Save kayoslab/66f5952959781f3a028aead540e5cc69 to your computer and use it in GitHub Desktop.
A Property wrapper around UserDefaults which makes it easier to interact with.
import Foundation
let defaults = UserDefaults(suiteName: "GistApplication")
/// A Property wrapper around UserDefaults which makes it easier to interact with.
@propertyWrapper struct UserDefault<T> {
/// The key of the entry which should be added to the defaults.
let key: String
/// Initialises a new entry.
///
/// - Parameter key: The key of the entry.
init(_ key: String) {
self.key = key
}
/// The actual value retrieved from the defults.
var wrappedValue: T? {
get {
return defaults?.object(forKey: key) as? T
}
set {
defaults?.set(newValue, forKey: key)
}
}
}
struct Settings {
// swiftlint:disable let_var_whitespace
@UserDefault("gist.version")
static var version: Int?
@UserDefault("gist.isEnabled")
private static var isEnabled: Bool?
// swiftlint:enable let_var_whitespace
static var featureIsEnabled: Bool {
get {
return Settings.isEnabled ?? false
}
set {
Settings.isEnabled = newValue
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment