swift - 基于另一个过滤数组

标签 swift filter

我有两个数组,一个是配置文件数组,另一个是部分名称:

var sections: [Array<Profile>] = [friends, contacts, other]
var sectionNames = ["Friends", "Contacts", "Other Users"]

如何根据部分是否为空来过滤名称?尝试以下代码时出现错误:

sectionNames.filter { index, _ in
    sections[index].count > 0
}

Contextual closure type '(String) throws -> Bool' expect 1 argument, but two given

最佳答案

您可以使用zipcompactMap:

let nonEmptySections = zip(sections, sectionNames).compactMap { $0.isEmpty ? nil : $1 }

使用 zip 的优点是,如果两个数组的大小不同,则不会发生崩溃。另一方面,它可能会导致细微的错误。

我建议您改用数据结构来为数据建模:

struct Section {
    let name: String
    let profiles: [Profile]
}

这应该会简化您处理应用中各个部分的方式。通过使用@Alexander 的建议,您可以将 isEmpty 属性添加到结构中,使其更易于使用

extension Section {
    var isEmpty: Bool { return profiles.isEmpty }
}

... later in the code

let nonEmptySections = sections.filter { !$0.isEmpty }

关于swift - 基于另一个过滤数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58207329/

相关文章:

filter - 在表格中排列过滤器值

ios - Swift 中的可选动态属性

ios - 创建我自己的导航栏

ios - 当我滚动时,UICollectionViewCell 混淆了

javascript - 如何在 AngularJS 中使用 ngTable 搜索过滤日期对象

python - python 中的 zip 和过滤器

swift - 在 Swift 中使用文本字段设置 MKAnnotation 的标题

ios - 如何在 swift 中延迟字符串插值?

json - 如何在 KQL 中找到动态数组中的特定元素?

c# - 如何从带有列表的对象列表创建列表