使用 Swift 将具有相同类型的字典分组到具有完整键和值的数组中

Group a dictionary with same type into an array with full key and value using Swift

好久没用了Swift.

我有一个这样的响应数据,我将它保存到一个名为 responseData:

的数组中
[
{
"type": "Switch",
"name": "Switch1",
"search_key": "is_promotion",
"key": "is_promotion=1",
"icon": ""
},
{
"type": "Switch",
"name": "Switch2",
"search_key": "shop_type",
"key": "shop_type=2",
"icon": ""
},
{
"type": "Switch",
"name": "Switch3",
"search_key": "is_certified",
"key": "is_certified=1",
"icon": ""
},
{
"type": "Switch",
"name": "Switch4",
"search_key": "shop_free_shipping",
"key": "shop_free_shipping=1",
"icon": ""
},
{
"type": "Switch",
"name": "Switch5",
"search_key": "is_loyalty",
"key": "is_loyalty=1",
"icon": ""
},
{
"type": "Switch",
"name": "Switch6",
"search_key": "is_using_instant",
"key": "is_using_instant=1",
"icon": ""
},
{
"type": "Switch",
"name": "Switch7",
"search_key": "is_installment",
"key": "is_installment=1",
"icon": ""
},
{
"type": "Range",
"name": "Price Range",
"search_key": "level_Price_Max_Min",
"value": [
{
"option_id": 0,
"option_name": 0
},
{
"option_id": 0,
"option_name": 10000000
}
]
},
{
"type": "ColorTerm",
"name": "Color",
"search_key": "color_key",
"value": [
{
"option_id": 605,
"value": "Black",
"color_id": 13,
"image": "",
"option_name": "Black",
"background": "#000000",
"option_active": "",
"facet_count": 52655
},

现在我想将类型为 Switch 的所有字典分组到一个数组中,我可以访问其中的键,然后呈现 Switch 类型数组和其他类型数组的数据 UITableView 有 2 个部分(Switch 在第 0 部分中键入)。我该怎么做?我必须搜索一些其他解决方案,但我不明白如何将它们应用到我的代码中以供工作。

这是我的 FilterModel class:

class FilterModel: NSObject, NSCoding, NSCopying {

    override func copy(with zone: NSZone? = nil) -> Any {
        // This is the reason why `init(_ model: GameModel)`
        // must be required, because `GameModel` is not `final`.
        let copy = FilterModel(dict: self.dictionary)

        if let arrAttribute = NSArray(array: self.value , copyItems: true) as? [AttributeValueModel] {
            copy.value = arrAttribute
        }

        return copy
    }

    override init(dict: Dictionary<String, Any>) {
        super.init(dict: dict);

        value = self.valueParse()
    }


    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    var name: String? {
        return self.dictionary.getString(forKey: "name")
    }

    var icon: String? {
        return self.dictionary.getString(forKey: "icon")
    }

    var search_key: String? {
        return self.dictionary.getString(forKey: "search_key")
    }

    var key: String? {
        return self.dictionary.getString(forKey: "key")
    }

    var type: FilterDisplayType {
        let type = self.dictionary.getString(forKey: "type")
        return self.getType(string: type)
    }

    var value: [AttributeValueModel] = [];


    func valueParse()-> [AttributeValueModel] {
        // with switch type, Just set true or false
        // Change ParentValue to Child
        if type == .Switch {
            let dict:Dictionary<String, AnyObject> = [
                "option_id": "false" as AnyObject,
                "option_name": self.name! as AnyObject,
                "name": self.name! as AnyObject,
                "icon": self.icon! as AnyObject
            ]

            let item = AttributeValueModel(dict:dict);
            return [item]
        }

        guard let childs  = (self.dictionary["value"]) as? [Dictionary<String, AnyObject>]
            else { return [] }

        var output: [AttributeValueModel] = [];

        for  aDict in childs {
            let item = AttributeValueModel(dict:aDict);

            if type == .Range  && item.option_id == "0" {
                item.setRangeOptionID(aValue: item.option_name!)
            }

            output.append(item);
        }

        return output;
    }

    ///get list AttributeValueModel Selected
    func selectedValues() -> [AttributeValueModel] {

        var output: [AttributeValueModel] = [];

        for itemTemp in self.value {
            if(itemTemp.selected){
                if type == .Switch {
                    itemTemp.setSelectedOptionID()
                }

                output.append(itemTemp);
            }
        }
        return output;
    }

    /// make a Filter Item from attributeValues Seleted
    func getFilterItem() -> FilterItem? {

        var itemFilter: FilterItem = FilterItem(key: self.search_key!, value: "")
        itemFilter.key = self.search_key!

        let output: NSMutableArray = [];

        for attItem in self.selectedValues() {
            if attItem.option_id != "" {
                output.add(attItem.option_id!);
            }
        }

        if(output.count == 0) {
            return nil;
        }

        let valueString = output.componentsJoined(by: ",");

        itemFilter.value = valueString;

        return itemFilter
    }

    ///get list AttributeValueModel Selected
    func resetToDefault() -> [AttributeValueModel] {

        var output: [AttributeValueModel] = [];

        for itemTemp in self.value {
            if(itemTemp.selected){
                itemTemp.selected = false

                if type == .Switch {
                    itemTemp.setSelectedOptionID()
                }

                if type == .Range {
                    itemTemp.setRangeOptionID(aValue: itemTemp.option_name!)
                }

                output.append(itemTemp);
            }
        }
        return output;
    }

    //for UI
    var wasExpanding = false
    var numberOfRow:Int = 0
    /************/

    var attributeNameLength: Int {
        var string = ""
        for item in valueParse() {
            string += item.option_name!
        }

        return string.count
    }

    var lenghtSizeName:Int {

        var row:Int = 1
        var width:CGFloat = 0
        let padding:CGFloat = 8

        let screen = screenWidth - 50 - 16
        for item in valueParse() {
            let size = ((item.option_name ?? "") as NSString).size(withAttributes: [
                NSAttributedStringKey.font : UIFont.fontRegular_Big()
                ])

            let totalWidth = size.width + padding + 16

            if totalWidth <= CGFloat(32) {
                width += 32
                if width >= screen {
                    row += 1
                    width = 32
                }
            } else {
                width += totalWidth
                if width >= screen {
                    row += 1
                    width = totalWidth
                }
            }
        }
        return row
    }

}

您可以过滤您的响应数据以在数组中获得 个开关。

responseData.filter {([=10=].type ?? "") == "Switch"}

当然 != 会给你无开关。