I have an array of objects like this stored in firestore: database
I have a model for the whole exercise:
import Foundation
import Firestore
protocol DocumentSerializable {
init?(dictionary:[String:Any])
}
struct Exercise {
var title: String
var language: String
var translated: String
var uid: String
var userId: String
var dueDate: Int
var lastOpen: Int
var words: Array<Any>
var dictionary:[String:Any] {
return [
"title":title,
"language":language,
"translated":translated,
"uid":uid,
"userId":userId,
"dueDate":dueDate,
"lastOpen":lastOpen,
"words":words
]
}
}
extension Exercise : DocumentSerializable {
init?(dictionary: [String : Any]) {
guard let title = dictionary["title"] as? String,
let language = dictionary["language"] as? String,
let translated = dictionary["translated"] as? String,
let uid = dictionary["uid"] as? String,
let userId = dictionary["userId"] as? String,
let dueDate = dictionary["dueDate"] as? Int,
let lastOpen = dictionary["lastOpen"] as? Int,
let words = dictionary["words"] as? Array<Any>
else {return nil}
self.init(title: title, language: language, translated: translated, uid: uid, userId: userId, dueDate: dueDate, lastOpen: lastOpen, words: words)
}
}
I then want to get the words to a model like this:
import Foundation
import Firestore
protocol DocumentSerializable2 {
init?(dictionary:[String:Any])
}
struct Word {
var translation: String
var word: String
var dictionary:[String:Any] {
return [
"translation":translation,
"word":word
]
}
}
extension Word : DocumentSerializable2 {
init?(dictionary: [String : Any]) {
guard let translation = dictionary["translation"] as? String,
let word = dictionary["word"] as? String
else {return nil}
self.init(translation: translation, word: word)
}
}
I can then retrieve the data with this function:
func loadData() {
docRef = db.collection("exercises").document(exerciseId)
docRef.getDocument{ (docSnapshot, error) in
guard let docSnapshot = docSnapshot, docSnapshot.exists else { return }
let data = docSnapshot.data()
self.exerciseArray = docSnapshot.data().flatMap({_ in Exercise(dictionary: data)})
let exercise = self.exerciseArray[0]
print(exercise.words)
self.language1Label.text = exercise.language
self.translateLabel.text = exercise.translated
self.navigationItem.title = exercise.title
}
}
I can get the words to an array of objects and when printed the array looks like this: printed array
How do I now get the words to my word model? My own guess is that I should change how I save the words array in the exercise model but I can not wrap my head around how I would do that.
Thanks!