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
}
enum UserPreferenceFieldKey : String {
case userSelectedTags = "MLQUserSelectedTags"
case userLastActivePlalist = "MLQUserLastActivePlalist"
case userLastActivePlayableEntityMeta = "MLQUserLastActivePlayableEntityMeta"
case currentUSer
}
struct User : Codable {
let name : String
let phone: String
}
@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
}
}
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 error
}
}
}
But if the same is used in the same file it works fine with optional chaining.
As per the reply from Apple Developers Team on Dev forum, It's not happening in Xcode 11.3 and worked fine when added optional to declared property.