Search code examples
structswift3uisearchbaruisearchcontroller

How to filter the values of a string array in a struct object substring wise


I want to check a value is there in section object.This code is working fine but if I write the complete name only it will get in to the filtered object.i need to get the filtered data when the search test matches with a substring in the string array

["A": ["Affenpoo", "Affenpug", "Affenshire", "Affenwich", "Afghan Collie", "Afghan Hound"], "B": ["Bagle Hound", "Boxer"]]

        struct Objects {
             var sectionName : String!
             var sectionObjects : [String] 
             var sectionid:[String]!
             var sectionph:[String]!
             var sectionImage:[String]!
                }

        var objectArray = [Objects]()
        var objectArrayFilter = [Objects]()

    objectArrayFilter = objectArray.filter({$0.sectionObjects.contains(searchBar.text!)})

Solution

  • If you want filter like that if you enter string afg in UITextField then it should return only two object "Afghan Collie", "Afghan Hound" with section A, then you can make it like this.

    objectArrayFilter = objectArray.flatMap {
        var filterObjects = $0
        filterObjects.sectionObjects = $0.sectionObjects.filter { 
            $0.range(of : searchBar.text!, options: .caseInsensitive) != nil
        }
        return filterObjects.sectionObjects.isEmpty ? nil : filterObjects
    } 
    

    Edit: Struct that you have make is not proper what you need to do is make another struct and make with property object,id,ph and image all type of string and then make array of this struct inside your Object struct.

    struct SubObjects {
        var sectionObject: String!
        var sectionid: String!
        var sectionph: String!
        var sectionImage: String!
    }
    
    struct Objects {
        var sectionName : String!
        var sectionObjects : [SubObjects]! 
    }
    

    Now filter this way.

    var objectArray = [Objects]()
    var objectArrayFilter = [Objects]()
    
    objectArrayFilter = objectArray.flatMap {
        var filterObjects = $0
        filterObjects.sectionObjects = $0.sectionObjects.filter { 
            $0.sectionObject.range(of : searchBar.text!, options: .caseInsensitive) != nil
        }
        return filterObjects.sectionObjects.isEmpty ? nil : filterObjects
    }