```swift
import SwiftUI
struct TextItem:Identifiable,Codable{
var id = UUID().uuidString
var text:String = ""
}
//终于写出了范型,这个太好用了。每一种语法的出现都是为了解决一种问题,提供某种方便。
//使用方法 let dataSaver = DataSaver<你要保存的数据类型>()
class DataSaver<T:Codable>{
func saveData(items:[T],forkey:String){
let encode = JSONEncoder()
do{
let data = try encode.encode(items)
UserDefaults.standard.set(data, forKey: forkey)
}
catch
{
print(error.localizedDescription,"保存数据失败")
}
}
func fetchData(forkey:String)->[T]{
var results:[T] = []
let decode = JSONDecoder()
do{
if let data = UserDefaults.standard.data(forKey: forkey){
results =try decode.decode([T].self, from: data)
}
}
catch
{
}
return results
}
}
class ViewModel:ObservableObject{
//尖括号里指定范型的具体类型
let dataSaver = DataSaver<TextItem>()
@Published var textEditors:[TextItem] = []{
didSet{
saveData()
}
}
let textEditorsSaverKey:String = "textEditorsSaverKey"
init(){
fetchData()
}
func saveData(){
dataSaver.saveData(items: textEditors, forkey: textEditorsSaverKey)
}
func fetchData(){
self.textEditors = dataSaver.fetchData(forkey: textEditorsSaverKey)
}
}
//苹果应用商店|搜|王勋才|有我全部作品
```