Skip to content

Instantly share code, notes, and snippets.

@hishd
Created March 27, 2024 06:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hishd/47550b9a36b25b9cd2c3e784a6b9cfe5 to your computer and use it in GitHub Desktop.
Save hishd/47550b9a36b25b9cd2c3e784a6b9cfe5 to your computer and use it in GitHub Desktop.
//
// UserDefaults+Wrapper.swift
// SkyWizard
//
// Created by Hishara Dilshan on 2023-10-22.
//
import Foundation
import Combine
protocol AnyOptional {
var isNil: Bool {get}
}
extension Optional: AnyOptional {
var isNil: Bool {
return self == nil
}
}
@propertyWrapper
struct UserDefault<Value> {
let key: String
var defaultValue: Value
var container: UserDefaults = UserDefaults.standard
private let publisher = PassthroughSubject<Value, Error>()
var wrappedValue: Value {
get {
container.object(forKey: key) as? Value ?? defaultValue
}
set {
if let value = newValue as? AnyOptional, value.isNil {
container.removeObject(forKey: key)
} else {
container.set(newValue, forKey: key)
}
}
}
var projectedValue: AnyPublisher<Value, Error> {
publisher.eraseToAnyPublisher()
}
}
extension UserDefault where Value: ExpressibleByNilLiteral {
init(key: String,_ container: UserDefaults = UserDefaults.standard) {
self.init(key: key, defaultValue: nil, container: container)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment