Swift :从 JSON 转换为

Swift : Convert to from JSON

我将 Appwrite 与 Swift 一起使用,我正在尝试使用 convertTo 函数来获取文档的 JSON 结构,但我不确定如何继续。

这是我想使用的功能

public func convertTo<T>(fromJson: ([String: Any]) -> T) -> T {
    return fromJson(data)
}

这是我的代码(我正在尝试将 documentLits.documents 中的每个文档转换为 LocationAP 结构) :

Task {
    let documentList = try await AppwriteVM.instance.database.listDocuments(
        collectionId: "626b97104b392350d53e"
    )

    for document in documentList.documents {
        let decodedDocument: LocationAP = document.convertTo(fromJson: ?????)
        print(decodedDocument.name)
    }
}

这是 LocationAP 结构的定义:

struct LocationAP: Codable {
    var id: String
    var name: String
    var latitude: Double
    var longitude: Double
}

我的问题是我不确定如何继续 document.convertTo(fromJson: <#T##([String : Any]) -> T#> ) 函数,这里是我的代码截图:

code screenshot

有人知道如何进行吗?

正如 Joakim 所说,您必须编写一个包含如何转换字典的代码的闭包

let converter : ([String:Any]) -> LocationAP = { dictionary in
    // do the conversion and 
    // return a LocationApi instance
}

for document in documentList.documents {
    let decodedDocument = document.convertTo(fromJson: converter)
    print(decodedDocument.name)
}