0

谢谢你的帮助。我需要在我的 macOS Swift 应用程序中与 Toml 文件进行交互。我正在使用TOMLDecoder库来解析 Toml 格式。该库通过指定符合 Codable 的 Swift 结构类型来工作,并让库为我们创建对象。从文档:

struct Discography: Codable {
    struct Album: Codable {
       let name: String
       struct Song: Codable {
          let name: String
       }
       let songs: [Song]
    }
    let albums: [Album]
}

如果我们采用一个示例 Toml 文件:

[[albums]]
name = "Born to Run"

    [[albums.songs]]
    name = "Jungleland"

    [[albums.songs]]
    name = "Meeting Across the River"

[[albums]]
name = "Born in the USA"

  [[albums.songs]]
  name = "Glory Days"

  [[albums.songs]]
  name = "Dancing in the Dark"

我们可以解析它:

let tomlData = try? Data(contentsOf: URL(fileURLWithPath: "/path/to/file"))
let discography = try? TOMLDecoder().decode(Discography.self, from: tomlData)

我的问题来了。该库没有提供反转过程的方法,因此要序列化对象,所以我想自己编写它,如果我理解正确的话,我可能想用干净的 Swift 实现解决方案,通过使用 T 类型,从而允许任何类型的 Codable 符合对象可序列化。库中的解码函数为:

public func decode<T: Decodable>(_ type: T.Type, from text: String) throws -> T {
    let topLevel: Any
    do {
        topLevel = try TOMLDeserializer.tomlTable(with: text)
    } catch {
        throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: [], debugDescription: "The given data was not valid TOML.", underlyingError: error))
    }

    let decoder = TOMLDecoderImpl(referencing: self, options: self.options)
    guard let value = try decoder.unbox(topLevel, as: type) else {
        throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: [], debugDescription: "The given data did not contain a top-level value."))
    }

    return value
}

我已经开始编写我的编码函数,如下所示:

class TOMLEncoder: TOMLDecoder {

    func encode<T>(sourceObject: T) -> String {
    
        return "Sample serialized text..."
    
    }

}

我真的不知道如何继续......根据我非常有限的知识,我应该以某种方式迭代 sourceObject 属性并根据这些属性的内容创建 TOML 文件,但我不确定这是否是正确的方法以及如何实现它。任何帮助是极大的赞赏。谢谢

4

0 回答 0