Xcode 9.4.1 Swift 4 - 将非原始集与包含 Int 的原始集进行比较 [英] Xcode 9.4.1 Swift 4 - Comparing a non-primitive Set to a primitive set containing Int
问题描述
我对如何处理这种情况感到困惑,因为我无法弄清楚如何在返回 true 之前检查 listGroup 的每个列表中的单个值是否存在,以及如果 func 必须返回的 4 个列表之一中缺少一个值假的.
I am stumped on how to approach this scenario as I cannot figure out how to check if a single value within each list of the listGroup Exists before returning true and if one value is missing from one of the 4 lists the func must return false.
粘贴过来的列表会有一个包含id、name、group的数据结构在 objList 中传递的对象示例:对象 - id: Int, name: String, group: String
The list pasted through will have a data structure containing id, name, group Example of the object passed through within objList: Object - id: Int, name: String, group: String
init(){
//contains value which will match objList id's
let list1 : Set<Int> = [1,2]
let list2 : Set<Int> = [3,4]
let list3 : Set<Int> = [5,6,7]
let list4 : Set<Int> = [8,9]
//Set of Sets
listGroups = [list1,list2,list3,list4]
}
func checklist(_ objList: [Details]) -> Bool {
//I want to check that each sub set(list1-list4) elements exist
//E.G. if objList contains 2, 3, 7, 8, 15, 21 it will return true
//and if objList contains 1, 4, 7, return false as it doesn't contain a
//number from each set
//How I thought to approach but became stuck
for obj in objList {
for set in listGroups {
if set.contains(i.id){
//return true if objList contains numbers from list1, list2, list3 and list4
}
}
}
//I require an id from each list to be present in the objList
//but how would i know which set had which id and count how many group of 4
//there would be
}
传递的详细信息"包含有关它们的详细信息,但是我想要做的是检查传递的 objList 中 listGroups 中的 Int 是否存在.然而,只有当 listGroups 的每个子集存在一个值时,func 才能返回 true.
The "Details" passed through contain details about them, however what I want to do is check whether the Int within the listGroups exist within the objList passed through. However the func can only return true if a value from each of the sub-sets of listGroups exists.
必须存在来自所有 4 个子集的单个值才能返回 true,如果缺少一个或多个,func 必须返回 false
A single value from all 4 subsets must be present before I can return true and if a single one or more is missing func must return false
推荐答案
从 itemList
的 id
值创建一个 Set
并使用 intersection
检查一个集合是否至少包含另一个集合的一个项目.
Create a Set
from the id
values of itemList
and use intersection
to check if one set contains at least one item of another set.
func checklist(_ objList: [Details]) -> Bool {
let idSet = Set(objList.map{$0.id})
for set in listGroups {
if set.intersection(idSet).isEmpty { return false }
}
return true
}
对于很长的列表,从 idSet
func checklist(_ objList: [Details]) -> Bool {
var idSet = Set(objList.map{$0.id})
for set in listGroups {
let commonSet = set.intersection(idSet)
if commonSet.isEmpty { return false }
idSet.subtract(set)
}
return true
}
这篇关于Xcode 9.4.1 Swift 4 - 将非原始集与包含 Int 的原始集进行比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!