2017-09-19 84 views
2

我正在使用sqlite文件從authorId中獲取diaryEntriesTeacher。它產生的AuthorID的下列對象時我打印變量的AuthorID是零 代碼: -swift 3.0如何在Swift 3的`Any`中訪問`AnyHashable`類型?

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() 
} 

輸出 enter image description here

+0

我想在這裏找到你要找的解決方案: [https://stackoverflow.com/questions/39864381/how-can-i-access-anyhashable-types-in-any-in-迅速](https://stackoverflow.com/questions/39864381/how-can-i-access-anyhashable-types-in-any-in-swift) – Diego

回答

0

這是你如何訪問[AnyHashable : Any]

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

字典在你案例

let authorId = totalCount?["authorId"] as? String ?? "" 
0

在使用它之前,我們需要將我們嘗試訪問的屬性轉換爲AnyHashable。

你的情況:

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

這是斯威夫特。使用強類型和快速枚舉。 Dictionary<AnyHashable,Any>是字典的通用類型,可以輸入到<String,Any>,因爲所有密鑰似乎都是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") 
     } 
    } 
....