0

it's been a long time I don't use Swift.

I have a response data like this and I saved it into an array named 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
},

Now I wanna group all dictionary with type Switch into one array and I can access to the keys inside it, then present data of both Switch type array and the others type on a UITableView which have 2 section (Switch type in section 0). How can I do it? I have to search some other solution but I don't understand how to apply them to my code for work.

Here is my 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
    }

}
2
  • Explain how you have decoded the data and the definition (data structure) of the array Dec 1, 2019 at 8:48
  • @JoakimDanielson I updated my filterModel class Dec 2, 2019 at 2:23

1 Answer 1

1

You can filter your response data to get only switches in an array.

responseData.filter {($0.type ?? "") == "Switch"}

And of course != would give you non switches.

2
  • I'm getting error at $0. It's say Type 'FilterModel' has no subscript member. I'm create my responseData like this: var responseData : [FilterModel]? Dec 1, 2019 at 7:33
  • Well then you should provide your filterModel in question, however i'm assuming type is an string variable, check the updated answer
    – Don
    Dec 1, 2019 at 8:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.