swift 3.0 How can I access `AnyHashable` types in `Any` in Swift 3?

11.4k views Asked by At

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

3

There are 3 answers

0
Sandeep Bhandari On BEST ANSWER

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 ?? ""
0
Surya Narayan Barik On

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
vadian On

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")
      }
  }
....