@@ -79,6 +79,33 @@ class MappingSimpleTypesViewModel: ObservableObject {
7979 private func fetchBook( documentId: String ) {
8080 let docRef = db. collection ( " books " ) . document ( documentId)
8181
82+ docRef. getDocument ( as: Book . self) { result in
83+ switch result {
84+ case . success( let book) :
85+ // A Book value was successfully initialized from the DocumentSnapshot.
86+ self . book = book
87+ self . errorMessage = nil
88+ case . failure( let error) :
89+ // A Book value could not be initialized from the DocumentSnapshot.
90+ switch error {
91+ case DecodingError . typeMismatch( _, let context) :
92+ self . errorMessage = " \( error. localizedDescription) : \( context. debugDescription) "
93+ case DecodingError . valueNotFound( _, let context) :
94+ self . errorMessage = " \( error. localizedDescription) : \( context. debugDescription) "
95+ case DecodingError . keyNotFound( _, let context) :
96+ self . errorMessage = " \( error. localizedDescription) : \( context. debugDescription) "
97+ case DecodingError . dataCorrupted( let key) :
98+ self . errorMessage = " \( error. localizedDescription) : \( key) "
99+ default :
100+ self . errorMessage = " Error decoding document: \( error. localizedDescription) "
101+ }
102+ }
103+ }
104+ }
105+
106+ private func fetchBookOptional( documentId: String ) {
107+ let docRef = db. collection ( " books " ) . document ( documentId)
108+
82109 // If you expect that a document might *not exist*, use an optional type (Book?.self)
83110 // and then perform an `if let book = book` dance to handle this case.
84111 docRef. getDocument ( as: Book ? . self) { result in
0 commit comments