【问题标题】:swift 3.0 How can I access `AnyHashable` types in `Any` in Swift 3?swift 3.0 如何在 Swift 3 的“Any”中访问“AnyHashable”类型?
【发布时间】:2018-02-27 21:37:34
【问题描述】:

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

输出

【问题讨论】:

标签: ios swift3 fmdb hashable


【解决方案1】:

这是您访问[AnyHashable : Any]字典的方式

var dict : Dictionary = Dictionary<AnyHashable,Any>()
dict["name"] = "sandeep"
let myName : String = dict["name"] as? String ?? ""

你的情况

let authorId = totalCount?["authorId"] as? String ?? ""

【讨论】:

    【解决方案2】:

    我们需要在使用之前将我们试图访问的属性转换为 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)
       }
    

    【讨论】:

      【解决方案3】:

      这是斯威夫特。使用强类型和快速枚举。 Dictionary&lt;AnyHashable,Any&gt; 是字典的通用类型,可以转换为 &lt;String,Any&gt;,因为所有键似乎都是 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")
            }
        }
      ....
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-11-14
        • 1970-01-01
        • 2021-05-09
        • 1970-01-01
        • 1970-01-01
        • 2022-10-01
        • 1970-01-01
        相关资源
        最近更新 更多