0

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?

Émile
  • 5
  • 1
  • You are supposed to write a [closure](https://docs.swift.org/swift-book/LanguageGuide/Closures.html) that takes a dictionary as input and returns an instance of LocationAP – Joakim Danielson Apr 30 '22 at 08:43

1 Answers1

1

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)
}
vadian
  • 274,689
  • 30
  • 353
  • 361