我正在使用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()
}
这是您访问[AnyHashable : Any]
字典的方法
var dict : Dictionary = Dictionary<AnyHashable,Any>()
dict["name"] = "sandeep"
let myName : String = dict["name"] as? String ?? ""
在你的情况下
let authorId = totalCount?["authorId"] as? String ?? ""
我们需要在使用之前将我们尝试访问的属性转换为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)
}
这是斯威夫特。使用强类型和快速枚举。 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")
}
}
....