在 Swift 上自动创建 arraylist 对象
Posted
技术标签:
【中文标题】在 Swift 上自动创建 arraylist 对象【英文标题】:create arraylist objects automatically on Swift 【发布时间】:2020-03-23 16:49:50 【问题描述】:我有一个列表,我想根据我想要获得的属性进行划分。 例如。如果有这个列表,我想使用一个主列表创建 3 个不同的列表。
var companiesf = [
Directory(directoryId: 1, fullname: "Jose Luis", company: "A"),
Directory(directoryId: 2, fullname: "Fernando", company: "A"),
Directory(directoryId: 3, fullname: "Maria", company: "B"),
Directory(directoryId: 4, fullname: "Rodrigo", company: "B"),
Directory(directoryId: 5, fullname: "Miguel", company: "C")
]
最后,我想得到这个结果
var listA = [
Directory(directoryId: 1, fullname: "Jose Luis", company: "A"),
Directory(directoryId: 2, fullname: "Fernando", company: "A")
]
var listB = [
Directory(directoryId: 3, fullname: "Maria", company: "B"),
Directory(directoryId: 4, fullname: "Rodrigo", company: "B")
]
var listC = [
Directory(directoryId: 5, fullname: "Miguel", company: "C")
]
但我不知道如何自动创建数组对象
非常感谢!
【问题讨论】:
【参考方案1】:您可以通过创建分组字典来创建公司数组
let groupedByCompany = Dictionary(grouping: companiesf, by: $0.company)
然后从中创建你的数组
let listA = grouped["A", default: []]
let listB = grouped["B", default: []]
let listC = grouped["C", default: []]
另一种选择是使用filter
let listA = companiesf.filter $0.company == "A"
let listB = companiesf.filter $0.company == "B"
let listC = companiesf.filter $0.company == "C"
【讨论】:
谢谢。你知道如何在 Foreach 中阅读“groupedByCompany”吗? 你的意思是像this question以上是关于在 Swift 上自动创建 arraylist 对象的主要内容,如果未能解决你的问题,请参考以下文章
Swift - UICollectionView:如何在标题中自动布局标签间距