Swiftui 如何附加到结构数组并使更改持久化?

Swiftui 如何附加到结构数组并使更改持久化?,swiftui,swift5,swiftui-list,Swiftui,Swift5,Swiftui List,我希望能够将对象列表存储在单独的Swift文件中,并在页面中调用它们以显示它们。我成功地使用以下代码完成了此操作: import Foundation import SwiftUI struct MatchInfo: Hashable, Codable { let theType: String let theWinner: String let theTime: String let id = UUID() } var matchInfo = [ Ma

我希望能够将对象列表存储在单独的Swift文件中,并在页面中调用它们以显示它们。我成功地使用以下代码完成了此操作:

import Foundation
import SwiftUI



struct MatchInfo: Hashable, Codable {
    let theType: String
    let theWinner: String
    let theTime: String
    let id = UUID()
}


var matchInfo = [
MatchInfo(theType: "Capitalism", theWinner: "Julia", theTime: "3/3/2021"),
MatchInfo(theType: "Socialism", theWinner: "Julia", theTime: "3/2/2021"),
MatchInfo(theType: "Authoritarianism", theWinner: "Luke", theTime: "3/1/2021")
]
其中,在另一个页面上播放比赛后,我将添加到列表中:

 matchInfo.insert(MatchInfo(theType: typeSelection, theWinner: winnerName, theTime: "\(datetimeWithoutYear)" + "\(year)"), at: 0)
下面是另一页上的一些代码,我将其称为列表:

List {
                    ForEach(matchInfo, id: \.self) { matchData in
                        
                        matchRow(matchData : matchData)
                        
                    } .background(Color("invisble"))
                    .listRowBackground(Color("invisble"))
                } .frame(height: 490)


但此代码不会通过应用程序重新启动保存。我以前从来没有通过重启来保存过东西,我一直在努力寻找一个简单到我能理解的答案。下次打开应用程序时,如何更新列表而不使其消失?

好的,下面是一个关于如何保存到文档文件夹或从文档文件夹加载的示例

首先,确保对象MatchInfo符合此协议

import Foundation

protocol LocalFileStorable: Codable {
    static var fileName: String { get }
}

extension LocalFileStorable {
    static var localStorageURL: URL {
        guard let documentDirectory = FileManager().urls(for: .documentDirectory, in: .userDomainMask).first else {
            fatalError("Can NOT access file in Documents.")
        }
        
        return documentDirectory
            .appendingPathComponent(self.fileName)
            .appendingPathExtension("json")
    }
}

extension LocalFileStorable {
    static func loadFromFile() -> [Self] {
        do {
            let fileWrapper = try FileWrapper(url: Self.localStorageURL, options: .immediate)
            guard let data = fileWrapper.regularFileContents else {
                throw NSError()
            }
            return try JSONDecoder().decode([Self].self, from: data)
            
        } catch _ {
            print("Could not load \(Self.self) the model uses an empty collection (NO DATA).")
            return []
        }
    }
}

extension LocalFileStorable {
    static func saveToFile(_ collection: [Self]) {
        do {
            let data = try JSONEncoder().encode(collection)
            let jsonFileWrapper = FileWrapper(regularFileWithContents: data)
            try jsonFileWrapper.write(to: self.localStorageURL, options: .atomic, originalContentsURL: nil)
        } catch _ {
            print("Could not save \(Self.self)s to file named: \(self.localStorageURL.description)")
        }
    }
}

extension Array where Element: LocalFileStorable {
    ///Saves an array of LocalFileStorables to a file in Documents
    func saveToFile() {
        Element.saveToFile(self)
    }
}
您的主要内容视图应该如下所示:(我修改了您的对象,使其更简单。)


谢谢,我想说的是,我可以成功地将它添加到我的列表中,并在其他地方显示出来,但我不知道如何通过应用程序重启来保存它。你有没有可能在这里告诉我该怎么做?我更新了答案并添加了一个代码示例。
import Foundation

protocol LocalFileStorable: Codable {
    static var fileName: String { get }
}

extension LocalFileStorable {
    static var localStorageURL: URL {
        guard let documentDirectory = FileManager().urls(for: .documentDirectory, in: .userDomainMask).first else {
            fatalError("Can NOT access file in Documents.")
        }
        
        return documentDirectory
            .appendingPathComponent(self.fileName)
            .appendingPathExtension("json")
    }
}

extension LocalFileStorable {
    static func loadFromFile() -> [Self] {
        do {
            let fileWrapper = try FileWrapper(url: Self.localStorageURL, options: .immediate)
            guard let data = fileWrapper.regularFileContents else {
                throw NSError()
            }
            return try JSONDecoder().decode([Self].self, from: data)
            
        } catch _ {
            print("Could not load \(Self.self) the model uses an empty collection (NO DATA).")
            return []
        }
    }
}

extension LocalFileStorable {
    static func saveToFile(_ collection: [Self]) {
        do {
            let data = try JSONEncoder().encode(collection)
            let jsonFileWrapper = FileWrapper(regularFileWithContents: data)
            try jsonFileWrapper.write(to: self.localStorageURL, options: .atomic, originalContentsURL: nil)
        } catch _ {
            print("Could not save \(Self.self)s to file named: \(self.localStorageURL.description)")
        }
    }
}

extension Array where Element: LocalFileStorable {
    ///Saves an array of LocalFileStorables to a file in Documents
    func saveToFile() {
        Element.saveToFile(self)
    }
}
import SwiftUI

struct MatchInfo: Hashable, Codable, LocalFileStorable {
    static var fileName: String {
        return "MatchInfo"
    }
    
    let description: String
}

struct ContentView: View {
    @State var matchInfos = [MatchInfo]()
    
    var body: some View {
        VStack {
            Button("Add Match Info:") {
                matchInfos.append(MatchInfo(description: "Nr." + matchInfos.count.description))
                MatchInfo.saveToFile(matchInfos)
            }
            List(matchInfos, id: \.self) {
                Text($0.description)
            }
            .onAppear(perform: {
                matchInfos = MatchInfo.loadFromFile()
            })
        }
    }
}