Skip to content

Instantly share code, notes, and snippets.

@muizidn
Created July 15, 2019 06:54
Show Gist options
  • Save muizidn/f58a14efbe5ce7eb28642b7edb85d382 to your computer and use it in GitHub Desktop.
Save muizidn/f58a14efbe5ce7eb28642b7edb85d382 to your computer and use it in GitHub Desktop.
Make your User Default TypeSafe.
import Foundation
// UserDefault is threadsafe
// https://developer.apple.com/documentation/foundation/userdefaults
struct State<T>: Equatable where T: Codable & Equatable {
fileprivate let id: String
fileprivate let `default`: T
}
extension State {
static var isFirstTime: State<Bool> {
return .init(id: "isFirstTime", default: true) }
}
class AppState {
private init() {}
static func get<T>(_ state: State<T>) -> T {
let value = UserDefaults.standard.value(forKey: state.id) as? T
return value ?? state.default
}
static func set<T>(_ state: State<T>, newValue: T) {
UserDefaults.standard.set(newValue, forKey: state.id)
}
}
#if DEBUG
// MARK: Usage
func usage() {
if AppState.get(.isFirstTime) {
print("Login")
} else {
print("Dashboard")
}
}
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment