我有两个数组,一个是配置文件数组,另一个是部分名称:
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
最佳答案
您可以使用zip
和compactMap
:
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/