I have a structure TodoItem
struct TodoItem: Codable, Hashable, Identifiable {
var id: UUID = UUID()
var item: String
var done: Bool = false
}
How can I use AppStorage on [TodoItem]
?
OK found it out myself: https://www.jianshu.com/p/7591a7cd5eb1
I can do
extension Array: RawRepresentable where Element: Codable {
public init?(rawValue: String) {
guard let data = rawValue.data(using: .utf8),
let result = try? JSONDecoder().decode([Element].self, from: data)
else { return nil }
self = result
}
public var rawValue: String {
guard let data = try? JSONEncoder().encode(self),
let result = String(data: data, encoding: .utf8)
else {
return "[]"
}
return result
}
}
Also Date:
extension Date: RawRepresentable{
public typealias RawValue = String
public init?(rawValue: RawValue) {
guard let data = rawValue.data(using: .utf8),
let date = try? JSONDecoder().decode(Date.self, from: data) else {
return nil
}
self = date
}
public var rawValue: RawValue{
guard let data = try? JSONEncoder().encode(self),
let result = String(data:data,encoding: .utf8) else {
return ""
}
return result
}
}