簡體   English   中英

如何在Swift中過濾字典數組

[英]How to filter an array of dictionaries in Swift

我選擇通過使用可變的字典對象數組填充NSTableview,其中字典鍵是列標識符,值是列值。 我這樣填充數組:

var compArray: NSMutableArray = []

let dict = ["idCompany": id, "company": companyName, "compType": 
companyType] as [String : Any]
            compArray.add(dict)

id,company和compType來自SQlite查詢。

我使用compArray作為tableView數據源。 這很好。 不涉及陣列控制器。

使用CDM如下加載表,CDM是提供compArray的類的實例。

//Define the function that will get the data for each cell for each 
//row.
func tableView(_ tableView: NSTableView, objectValueFor tableColumn: NSTableColumn?, row: Int) -> Any? {

    //Define constant dict as an NSDictionary and set to the DM 
    //instance of the DataModel class at the row being loaded into the 
    //table. DM needs to be cast as an NSDictionary. row is passed in as a 
    //parameter by the OS
    let tdict:NSDictionary = CDM.compArray[row] as! NSDictionary

    //Define strKey as the column identifier for the column being 
    //loaded. Column being loaded is passed in as a parameter by the OS
    let strKey = (tableColumn?.identifier)!

    //method will return the value from dict (which is loaded from 
    //CDM.compArray) for the key that is equal to the column identifier 
    //which was loaded to strKey
    return tdict.value(forKey: strKey.rawValue)
}

我想做的是引入一個NSSearch字段來搜索tableview的所有列。

我添加了searchfield作為操作,還添加了代碼以將compArray存儲到一個名為backupCompArray的副本中。

我定義了一個isSearching變量:

//The variable is set to true when searching
var isSearching = false {
    //This will be fired if the state of isSearching changes ie false 
    //to true or true to false
    didSet {

        //Test to see whether isSearching now has a new value and if 
        //so we do the housekeeping
        if isSearching != oldValue {

            //If isSearching is now true then it must have previously 
            //been false and we now need to back up the original array
            if isSearching {
                //Back up the original array
                backUpCompArray = compArray
            } else{
                //It is now turning from true to false so need to 
//restore
                compArray = backUpCompArray
            }
        }
    }
}

我希望能夠基於搜索字段的.stringValue過濾compArray。

我在搜索字段的@IBAction中添加了以下內容:

@IBAction func searchField(_ sender: NSSearchFieldCell) {
    if sender.stringValue.isEmpty {
        //If stringValue is empty then cant be searching and this can 
        //trigger the restore of the original array
        isSearching = false
    } else {

        //If stringValue is not empty then must be searching. When the 
        //search starts need to backup the original array
        isSearching = true

        //?????????????
        }
    }

    tableView.reloadData()
}

我需要更換嗎? 使用可以通過將過濾器應用於backupCompArray來設置compArray的代碼,將任何行返回到compArray,其中鍵“ company”和“ compType”的字典值包含searchfield.Stringvalue。 然后,我可以使用修改后的compArray來僅使用過濾后的行加載表。

因此,我嘗試了您的代碼,並遇到了兩個錯誤,並嘗試修復如下:

//Can use the .filter method it will iterate each value in the array
        CDM.compArray = backupCompArray.filter(using: {
            // this is where you determine whether to include the 
specific element, $0
            $0["company"]!.contains(sender.stringValue) &&
            $0["compType"]!.contains(sender.stringValue)
            // or whatever search method you're using instead
        })
    }

那就是插入“ using”並將searchString更改為sender.Stringvalue。

但是我現在得到: 在此處輸入圖片說明

以&&結尾的行

您可以使用Swift 4的Array.filter() 它具有一個可以執行計算的功能。 實際上,您實際上不需要備份compArray,除非以后需要保留它以備其他用途。

compArray = compArray.filter({
    // this is where you determine whether to include the specific element, $0
    $0["company"]!.contains(searchString) &&
    $0["compType"]!.contains(searchString)
    // or whatever search method you're using instead
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM