Last active
May 29, 2017 16:05
-
-
Save wookiee/10da210043b3ccb0e9ddb7d0b63f2888 to your computer and use it in GitHub Desktop.
Convenience wrapper for UserDefaults-bound computed properties
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
// | |
// UserDefault.swift | |
// | |
// Created by Michael L. Ward on 5/29/17. | |
// Copyright © Michael L. Ward. All rights reserved. | |
// | |
import Foundation | |
struct UserDefault<T> { | |
private let key: String | |
private let defaults: UserDefaults | |
var value: T? { | |
get { | |
let val = defaults.value(forKey: key) | |
guard let t = val as? T? else { | |
fatalError("Defaults object for key '\(key)' is of type \(type(of:val)), expected \(T.self)") | |
} | |
return t | |
} | |
set { | |
defaults.set(newValue, forKey: key) | |
} | |
} | |
init(key: String, value: T? = nil, defaults: UserDefaults = UserDefaults.standard) { | |
self.key = key | |
self.defaults = defaults | |
defaults.register(defaults: [key:value as Any]) | |
} | |
} | |
extension UserDefault where T == Bool { | |
var boolValue: Bool { | |
get { return self.value ?? false } | |
set { self.value = newValue } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment