Home > Net >  Swift : Convert to from JSON
Swift : Convert to from JSON

Time:05-01

I'm using Appwrite with Swift and I'm trying to use a convertTo function to get a JSON structure of a document but I'm not sure on how to proceed.

Here is the function I would like to use

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

And here is my code (I'm trying to convert each document in documentLits.documents into a LocationAP struct):

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)
    }
}

Here is the definition of the LocationAP struct:

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

My problem is that I'm not sure on how to proceed with the document.convertTo(fromJson: <#T##([String : Any]) -> T#>) function, here is a screenshot of my code:

code screenshot

Does anyone know how to proceed?

CodePudding user response:

As Joakim said you have to write a closure containing the code how to convert the dictionary

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)
}
  • Related