【问题标题】:How to filter the values of a string array in a struct object substring wise如何过滤结构对象子字符串中的字符串数组的值
【发布时间】:2017-08-22 12:33:37
【问题描述】:

我想检查部分对象中是否存在值。此代码工作正常,但如果我只写完整名称,它将进入过滤对象。当搜索测试匹配时,我需要获取过滤数据字符串数组中的子字符串

["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!)})

【问题讨论】:

  • 他们使用数组'我使用了结构,所以有些混乱
  • $0.sectionObjects 是数组,您必须检查该数组中的某些字符串是否包含搜索文本。
  • @ShintoJOSEPH 如果您搜索特定项目,接受的答案将返回内部数组 sectionObjects 中的所有对象,或者如果您在 textfiled afg 中输入类似的内容,那么它应该返回只有两个对象 "Afghan Collie", "Afghan Hound" 与 A 部分,我问这个是因为接受的答案将返回 sectionObjects 数组中的所有对象。

标签: struct swift3 uisearchbar uisearchcontroller


【解决方案1】:

如果你想要这样的过滤器,如果你在UITextField 中输入字符串 afg 那么它应该只返回两个对象 "Afghan Collie", "Afghan Hound"加上A部分,那么你就可以这样了。

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
} 

编辑:您所拥有的结构不正确,您需要做的是制作另一个结构并使用属性对象、id、ph 和图像制作所有类型的字符串,然后制作这个数组结构在你的对象结构中。

struct SubObjects {
    var sectionObject: String!
    var sectionid: String!
    var sectionph: String!
    var sectionImage: String!
}

struct Objects {
    var sectionName : String!
    var sectionObjects : [SubObjects]! 
}

现在以这种方式过滤。

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
}

【讨论】:

  • 欢迎朋友 :)
  • 在搜索时 name 出现在 session 的 name 字段中,但该部分的所有 id 和图像都出现在 filteredsection 对象中
  • 这个 ID 和图像的来源在你的问题中没有类似的东西
  • 如果结构对象包含 section_id 和 sectionoimages 怎么办
  • 您制作的结构不正确您需要做的是制作另一个结构并使用属性对象、id、ph 和图像制作所有类型的字符串,然后在您的对象中制作此结构的数组结构
【解决方案2】:

请尝试以下方法:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-15
    • 1970-01-01
    • 2019-04-04
    • 1970-01-01
    • 2019-07-29
    • 1970-01-01
    • 2019-05-02
    • 2021-06-06
    相关资源
    最近更新 更多