Swift 3.0 如何在 Any 中访问 AnyHashable 类型?

7
我正在使用 sqlite 文件从 authorId 中获取 diaryEntriesTeacher,但当我打印变量 authorId 时,它生成了以下对象,其中 authorId 为 nil。 代码:-

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

输出 这里输入图片描述


我认为在这里你会找到你一直在寻找的解决方案: https://stackoverflow.com/questions/39864381/how-can-i-access-anyhashable-types-in-any-in-swift - Diego
3个回答

7

这是访问 [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
这是Swift编程语言。使用强类型和快速枚举。 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")
      }
  }
....

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接