We appear to be missing something when it comes to a simple document read. We are using the Hotel structure presented in the documentation and one set of code works (from the documentation) and a another set of code does not (also from the docs)
In referencing the documentation here
This section of code works correctly.
let collection: Collection
do {
let maybeCollection = try self.database.createCollection(name: "hotel")
collection = maybeCollection
} catch {
print(error.localizedDescription)
return
}
let query = QueryBuilder.select(SelectResult.all()).from(DataSource.collection(collection))
do {
let results = try query.execute()
for row in results {
let docsProps = row.dictionary(at: 0)!
let docid = docsProps.string(forKey: "id")!
let name = docsProps.string(forKey: "name")!
let type = docsProps.string(forKey: "type")!
print("\(docid): \(name), \(type)")
when run, this outputs the docId, name and type to console.
However the code referenced in the link crashes on this line
this_hotel.id = thisJsonObj["id"] as! String
with a âThread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional valueâ
And the complete code
do {
let results = try query.execute()
for row in results {
let jsonString = row.toJSON()
let thisJsonObj:Dictionary =
try ( JSONSerialization.jsonObject(
with: jsonString.data(using: .utf8)!,
options: .allowFragments)
as? [String: Any])!
// Use Json Object to populate Native object
// Use Codable class to unpack JSON data to native object
//let this_hotel: Hotel = try JSONDecoder().decode(Hotel.self, from: jsonString.data(using: .utf8)!)
// ALTERNATIVELY unpack in steps
let hotelDocId = thisJsonObj["id"] as! String //crash here
let hotelName = thisJsonObj["name"] as? String
let hotelType = thisJsonObj["type"] as? String
print("\(hotelDocId): \(hotelName), \(hotelType)")
}
Note the only difference between the above code and the documentation is //let this_hotel is commented out and the docId etc are set to vars.
Also, using the exact code documentation also has errors on name, type and city lines as
âValue of optional type âString?â must be unwrapped to a value of type âStringââ
Not sure where we are going wrong. Any suggestions would be appreciated.