7

我正在使用 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()
}

输出 在此处输入图像描述

4

3 回答 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 ?? ""
于 2017-09-19T07:55:56.110 回答
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)
   }
于 2017-09-19T08:08:21.123 回答
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")
      }
  }
....
于 2017-09-19T08:14:08.880 回答