ios - 在 iOS 中不使用 NSDictionary 的情况下具有多种类型的 Swift 字典数组

标签 ios swift dictionary swift2

我一直在使用 NSDictionary 在 Swift(版本 7 beta 4)中处理一系列字典。该数组是包含不同数据类型的 fmdb 结果的集合。为了使用 swift 集合类型的过滤器功能,我想最终得到一组原生的 swift 字典。以下是我用于创建数组的查询函数的片段:

class func query(sql:String) -> [NSDictionary] {
    let dirPaths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory,.UserDomainMask, true)
    let docsDir = dirPaths[0] as String
    let databasePath:String = docsDir.stringByAppendingPathComponent("myDB.db")
    let db = FMDatabase(path: databasePath as String)
    var resultsArray:[NSDictionary] = []

    if db.open() {

        let results:FMResultSet? = db.executeQuery(sql, withArgumentsInArray: nil)
        while (results?.next() == true) {
            resultsArray.append(results!.resultDictionary()) //appending query result

        }
        db.close()

    } else {
        print("Error: \(db.lastErrorMessage())")
    }
    return resultsArray
}

我尝试使用 AnyObject,例如:

    class func query(sql:String) -> [[String:AnyObject]] {
    let dirPaths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory,.UserDomainMask, true)
    let docsDir = dirPaths[0] as String
    let databasePath:String = docsDir.stringByAppendingPathComponent("Kerbal.db")
    let db = FMDatabase(path: databasePath as String)
    var resultsArray:[[String:AnyObject]] = []

    if db.open() {

        let results:FMResultSet? = db.executeQuery(sql, withArgumentsInArray: nil)
        while (results?.next() == true) {
            resultsArray.append(results!.resultDictionary() as! Dictionary<String,AnyObject>)

        }
        db.close()

    } else {
        print("Error: \(db.lastErrorMessage())")
    }
    return resultsArray
}

但是我不能将诸如 resultsArray.filter({$0["fieldName"] == "part"}) 之类的过滤器与 AnyObject 一起使用。

我的问题:是否可以使用 native Swift 字典创建此数组,即使字典具有不同的类型?新的协议(protocol)扩展可以用在集合类型上来解决这个问题吗?

如有任何建议,我们将不胜感激。

最佳答案

如果您不知道要处理哪些对象,则必须像这样使用过滤器:

resultsArray.filter{ ($0["fieldName"] as? String) == "part"}

因此您可以选择将值转换为所需的类型并进行比较。

注意:我使用的是尾随闭包语法。

作为建议,我会使用一个包含字典的不同数组的元组:

// some dummy values
let resultsArray: [[String : AnyObject]] = [["Hi" : 3], ["Oh" : "String"]]

var result = (doubles: [[String : Double]](), strings: [[String : String]]())

// going through all dictionaries of type [String : AnyObject]
for dict in resultsArray {

    // using switch and pattern matching to cast them (extensible for more types)
    // you have to up cast the dictioanary in order to use patten matching
    switch dict as AnyObject {
    case let d as [String : Double]: result.doubles.append(d)
    case let s as [String : String]: result.strings.append(s)
    default: fatalError("unexpected type")
    }
}

return result

关于ios - 在 iOS 中不使用 NSDictionary 的情况下具有多种类型的 Swift 字典数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31629589/

相关文章:

ios - 如何使 collectionview 响应其自身 View 之外的平移手势

python - 如何在运行时从其他文件访问字典

dictionary - 如何漂亮地打印同步 map 的内容

objective-c - iOS CGRectOffset 和核心数据问题

ios - 使 UIView 固定位置到 UITableViewController 的顶部

ios - 触摸按钮时显示发光

python - 在 Dict 中使用循环 .setdefault 创建嵌套 Dict

ios - 快速从核心数据中获取特定的 uiimage

swift - 类型别名 "Bar"不是类型 "Foo"的成员

ios - 在应用程序内登录 iCloud