【问题标题】:Filter an array of objects by an array of dictionaries contained in the object通过对象中包含的字典数组过滤对象数组
【发布时间】:2017-01-28 22:04:50
【问题描述】:

所以我需要通过对象中包含的数组来过滤对象数组

对象看起来像这样

class thing {

let list = [stuff, stuff, stuff, stuff]

}

class stuff {

var name = "ugly"

}

数组长这样

thingArray = [thing, thing, thing, thing]

到目前为止我的代码看起来像这样

newArray = thingArray.filter { receipt in

return thing.thingArray.lowercaseString.containsString(searchText.lowercaseString)
        }

所以我的问题是我无法让这个函数工作,而我真正需要的是一种通过对象内部包含的数组过滤这个对象数组的方法。任何帮助都非常感谢。

附言我只是尝试过没有用:

test = thingArray.filter {$0.list.filter {$0.name.lowercaseString.containsString(searchText.lowercaseString) == true}}

【问题讨论】:

    标签: ios arrays swift filter


    【解决方案1】:

    如果我理解正确,你的问题可以这样解决:

    class thing {
    
    init(list: [String]) {
        self.list = list
    }
    
    var list: [String]
    
    }
    
    let thingArray = [thing(list: ["one", "two", "three"]), thing(list: ["uno", "due", "tre"]), thing(list: ["uno", "dos", "tres"])]
    
    let searchString = "uno"
    
    let result = thingArray.filter {
        $0.list.contains(searchString)
    }
    
    //it will print "uno", "due", "tre"
    result.first?.list
    

    【讨论】:

    • 如果你想让搜索不区分大小写,你可以这样做: let result = thingArray.filter { ($0.list.filter { $0.lowercased() == searchString.lowercased() }。第一个!= nil) }
    • @PCD 请注意,如果性能是一个问题,您可以使用 Set 而不是 Array 来加快速度
    猜你喜欢
    • 2019-07-30
    • 1970-01-01
    • 2022-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-27
    • 2019-05-05
    • 2021-08-28
    相关资源
    最近更新 更多