如果包含空数组,请在数组映射中使用“继续”

时间:2018-10-10 06:57:47

标签: ios arrays swift

我正在2D数组中进行过滤,我只想在每个部分中有任何值的情况下获得结果。

我的结构:

<form class="rates">
    <div class="date-range date-range-main">
        @include('components/input_date', [
            'name' => 'date_from',
            'inline' => TRUE,
            'value' => $date_range->get_start(),
            'label' => ''
        ])
        -
        @include('components/input_date', [
            'name' => 'date_to',
            'inline' => TRUE,
            'value' => $date_range->get_end(),
            'label' => ''
        ])
    </div>
    <button class="btn btn-primary" type="submit">
        {{uctrans('labels.search')}}
    </button>
</form>

在我的searchBarDelegate扩展名中,我通过以下方式过滤对象:

struct SectionObject: Comparable {
    var sectionName: String
    var sectionObjects: [SectionValues]

    static func < (lhs: TagObjects, rhs: TagObjects) -> Bool {
        return lhs.sectionName < rhs.sectionName
    }

    static func == (lhs: TagObjects, rhs: TagObjects) -> Bool {
        return lhs.sectionName == rhs.sectionName
    }
}

它可以按我希望的方式工作,但是有时结果可以为0(而不是nil),所以我不能使用//var filterArray: [SectionObject] func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { if searchText.isEmpty { filterArray = sectionsArray return } filterArray = sectionsArray.map({ let existingValues = $0.sectionObjects.filter({ $0.value.contains(searchText) }) // if existingValues.count == 0 { continue } return SectionObject.init(sectionName: $0.sectionName, sectionObjects: existingValues) }) } 来跳过该部分。

我可以通过再次过滤compactMap来解决此问题,但是我想知道是否可以在数组映射中仅包含sectionObjects.count != 0吗?

1 个答案:

答案 0 :(得分:1)

可以使用compactMap!只需返回nil而不是continue

filterArray = sectionsArray.compactMap({
    let existingValues = $0.sectionObjects.filter({ $0.value.contains(searchText) })
    if existingValues.isEmpty { return nil }
    return SectionObject.init(sectionName: $0.sectionName, sectionObjects: existingValues)
})

之所以可行,是因为compactMap将删除那些映射到nil的元素。