Created
March 7, 2017 00:24
-
-
Save pdarcey/3c36ecb5c6c5775dc9324e24b32cf6cb to your computer and use it in GitHub Desktop.
Stringly-typed API Replacement
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
// 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 | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Ideally, in
extension BoolDefaultSettable where BoolKey.RawValue == String
the functions would be static functions, so the calls in code would be something likeUserDefaults.Onboarding.set(true, forKey: .hasScannedPhotoLibrary)
instead ofUserDefaults.Onboarding().set(true, forKey: .hasScannedPhotoLibrary)