2017-09-19 63 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") 
     } 
    } 
....