Created
July 15, 2019 06:54
-
-
Save muizidn/f58a14efbe5ce7eb28642b7edb85d382 to your computer and use it in GitHub Desktop.
Make your User Default TypeSafe.
This file contains hidden or 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
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