swift 3.0如何在Swift 3中的`Any`中访问`AnyHashable`类型?

问题描述 投票:4回答:3

我正在使用sqlite文件从authorId获取diaryEntriesTeacher。当我打印变量authorId是nil代码时,它会生成authorId的以下对象: -

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

ios swift3 fmdb hashable
3个回答
3
投票

这是您访问[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")
      }
  }
....
© www.soinside.com 2019 - 2024. All rights reserved.