6

I'm using sqlite file to get the diaryEntriesTeacher from the authorId. it generates the following object of authorId when I print the variable authorId is nil Code :-

func applySelectQuery() {        
    checkDataBaseFile()
    objFMDB = FMDatabase(path: fullPathOfDB)
    objFMDB.open()
    objFMDB.beginTransaction()

    do {
        let results = try objFMDB.executeQuery("select * from diaryEntriesTeacher", values: nil)



        while results.next() {  
            let totalCount = results.resultDictionary
            let authorId = totalCount?["authorId"]! 
            print("authorId",authorId)
   }


    }
    catch {
        print(error.localizedDescription)
    }
    print(fullPathOfDB)
    self.objFMDB.commit()
    self.objFMDB.close()
}

output enter image description here

Jayprakash Singh
  • 1,199
  • 2
  • 11
  • 26
  • I think here you find the solution you were looking for: [https://stackoverflow.com/questions/39864381/how-can-i-access-anyhashable-types-in-any-in-swift](https://stackoverflow.com/questions/39864381/how-can-i-access-anyhashable-types-in-any-in-swift) – Diego Sep 19 '17 at 07:55

3 Answers3

7

This is how you access Dictionary of [AnyHashable : Any]

var dict : Dictionary = Dictionary<AnyHashable,Any>()
dict["name"] = "sandeep"
let myName : String = dict["name"] as? String ?? ""

In your case

let authorId = totalCount?["authorId"] as? String ?? ""
Sandeep Bhandari
  • 17,815
  • 5
  • 34
  • 65
0

We need to convert the property we are trying to access to AnyHashable before using it.

In your case :

do {
        let results = try objFMDB.executeQuery("select * from diaryEntriesTeacher", values: nil)



        while results.next() {  
            let totalCount = results.resultDictionary
            let authorId = totalCount?[AnyHashable("authorId")]! 
            print("authorId",authorId)
   }
0

This is Swift. Use strong types and fast enumeration. Dictionary<AnyHashable,Any> is the generic type of a dictionary and can be cast to <String,Any> as all keys seem to be String.

do
  if let results = try objFMDB.executeQuery("select * from diaryEntriesTeacher", values: nil) as? [[String:Any]]

      for item in results {
          let authorId = item["authorId"] as? String 
          let studentName = item["studentName"] as? String 
          print("authorId", authorId ?? "n/a") 
          print("studentName", studentName ?? "n/a")
      }
  }
....
vadian
  • 232,468
  • 27
  • 273
  • 287