// MARK: UserDefault Property Wrapper
@propertyWrapper
struct UserPreferenceField<T : Codable> {
let key: UserPreferenceFieldKey
var wrappedValue : T? {
get {
guard let decodedData = UserDefaults.standard.value(forKey: key.rawValue) as? Data else { return nil }
return try? JSONDecoder().decode(T.self, from: decodedData)
}
set {
do {
let encodedValue = try JSONEncoder().encode(newValue)
UserDefaults.standard.set(encodedValue, forKey: key.rawValue)
} catch {
print("Error in saving codable value - \(error.localizedDescription)")
}
}
}
init(key:UserPreferenceFieldKey) {
self.key = key
}
}
enum UserPreferenceFieldKey : String {
case userSelectedTags = "MLQUserSelectedTags"
case userLastActivePlalist = "MLQUserLastActivePlalist"
case userLastActivePlayableEntityMeta = "MLQUserLastActivePlayableEntityMeta"
case currentUSer
}
struct HarkAppPreference {
@UserPreferenceField(key: .userSelectedTags)
static var userSelectedTags: [MLQTag]
@UserPreferenceField(key: .userLastActivePlalist)
static var userLastActivePlaylist: [PlayableEntity]
@UserPreferenceField(key: .userLastActivePlayableEntityMeta)
static var userLastActivePlayableEntityMeta: LastPlayableEntityMeta
@UserPreferenceField(key: .currentUSer)
static var user: User
}
This is my PropertyWrapper which I created to use for saving data to UserDefault, this worked to my expectations to use the value with optional chaining if used from within the file where I have written the PropertyWrapper code.
But this given an error Initializer for conditional binding must have Optional type, not 'User' when used in another file like below
class ABC {
func sss(){
if let _ = HarkAppPreference.user { // here is gives errorwhen used in other file but work ok if used in same file
}
}
}