Last active
November 3, 2020 08:02
-
-
Save IuriiIaremenko/bb882eec8ee1973a8590221bf23f8980 to your computer and use it in GitHub Desktop.
UserDefaults with Property Wrapper
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 Iurii Iaremenko on 24.10.2019. | |
// | |
import Foundation | |
@propertyWrapper | |
struct UserDefault<T> { | |
let key: String | |
let defaultValue: T | |
init(_ key: String, defaultValue: T) { | |
self.key = key | |
self.defaultValue = defaultValue | |
UserDefaults.standard.register(defaults: [key: defaultValue]) | |
} | |
var wrappedValue: T { | |
get { | |
UserDefaults.standard.object(forKey: key) as? T ?? defaultValue | |
} | |
set { | |
UserDefaults.standard.set(newValue, forKey: key) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment