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

3

7

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

Puny answered 19/9, 2017 at 7:40 Comment(1)
I think here you find the solution you were looking for: https://mcmap.net/q/1481035/-how-can-i-access-anyhashable-types-in-any-in-swiftDiploma
P
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 ?? ""
Pride answered 19/9, 2017 at 7:55 Comment(0)
U
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)
   }
Unstoppable answered 19/9, 2017 at 8:8 Comment(0)
G
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")
      }
  }
....
Gasometry answered 19/9, 2017 at 8:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.