要查找重复项,可以按电话号码建立交叉引用,然后将其过滤为仅重复项。例如,考虑:
let contacts = [ Contact(name: "Rob", phone: "555-1111"), Contact(name: "Richard", phone: "555-2222"), Contact(name: "Rachel", phone: "555-1111"), Contact(name: "Loren", phone: "555-2222"), Contact(name: "Mary", phone: "555-3333"), Contact(name: "Susie", phone: "555-2222")]
在Swift 4中,您可以使用以下命令构建交叉引用字典:
let crossReference = Dictionary(grouping: contacts, by: {let crossReference = contacts.reduce(into: [String: [Contact]]()) {.phone })let duplicates = crossReference .filter { .count > 1 } // filter down to only those with multiple contacts .sorted {[.phone, default: []].append()}Contact.1.count > .1.count } // if you want, sort in descending order by number of duplicates
要么
struct Contact { let name: String let phone: String}
然后,找到重复项:
flatMap
显然,请使用对您有意义的任何模型类型,但是上面的模型使用以下
let flattenedDuplicates = crossReference .filter { .count > 1 } // filter down to only those with multiple contacts .flatMap { .1 } // flatten it down to just array of contacts that are duplicates of something else类型:
有很多方法可以实现此目的,因此我将不再关注上述实现细节,而是关注以下概念:通过某个键(例如电话号码)构建交叉引用原始数组,然后将结果过滤为那些具有重复值的键。
听起来您想将反映重复项的结构扁平化为单个联系人数组(我不确定为什么要这么做,因为您丢失了标识彼此重复的结构),但是如果您想这样做,可以:
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)