Skip to content

Instantly share code, notes, and snippets.

@pdarcey
Created March 7, 2017 00:24
Show Gist options
  • Save pdarcey/3c36ecb5c6c5775dc9324e24b32cf6cb to your computer and use it in GitHub Desktop.
Save pdarcey/3c36ecb5c6c5775dc9324e24b32cf6cb to your computer and use it in GitHub Desktop.
Stringly-typed API Replacement
// MARK: - Use Enums for getting/setting User Defaults
protocol KeyNameSpaceable {
func namespaced<T: RawRepresentable> (_ key: T) -> String
}
extension KeyNameSpaceable {
func namespaced<T: RawRepresentable> (_ key: T) -> String {
return "\(Self.self).\(key.rawValue)"
}
}
protocol BoolDefaultSettable: KeyNameSpaceable {
associatedtype BoolKey: RawRepresentable
}
extension BoolDefaultSettable where BoolKey.RawValue == String {
func set(_ value: Bool, forKey key: BoolKey) {
let key = namespaced(key)
UserDefaults.standard.set(value, forKey: key)
}
func bool(forKey key: BoolKey) -> Bool {
let key = namespaced(key)
return UserDefaults.standard.bool(forKey: key)
}
}
extension UserDefaults {
struct Onboarding: BoolDefaultSettable {
enum BoolKey : String {
case hasRunBefore
case hasShownOnboarding
case isCheckingLocations
case hasScannedPhotoLibrary
}
}
struct Switches: BoolDefaultSettable {
enum BoolKey : String {
case photosSwitch
case facebookSwitch
case twitterSwitch
case israelSwitch
case chinaSwitch
case crimeaSwitch
case kosovoSwitch
case purchasesState
}
}
}
@pdarcey
Copy link
Author

pdarcey commented Mar 7, 2017

Ideally, in extension BoolDefaultSettable where BoolKey.RawValue == String the functions would be static functions, so the calls in code would be something like
UserDefaults.Onboarding.set(true, forKey: .hasScannedPhotoLibrary) instead of
UserDefaults.Onboarding().set(true, forKey: .hasScannedPhotoLibrary)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment