Xcode 9.4.1 Swift 4-将非原始集与包含Int的原始集进行比较

时间:2018-12-06 11:54:06

标签: swift set

我对如何处理这种情况感到困惑,因为我无法弄清楚如何在返回true之前检查listGroup的每个列表中是否存在单个值,以及如果4个列表之一中缺少一个值,则func必须返回错误。

粘贴的列表将具有包含id,name,group的数据结构 在objList中传递的对象的示例: 对象-id:整数,名称:字符串,组:字符串

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
}

传递的“详细信息”包含有关它们的详细信息,但是我想做的是检查listGroups中的Int是否在传递的objList中存在。但是,只有在listGroups的每个子集中都有一个值时,func才能返回true。

在我可以返回true之前,必须存在所有4个子集中的单个值,如果缺少一个或多个func,则必须返回false

1 个答案:

答案 0 :(得分:3)

根据Set的{​​{1}}个值创建一个id,然后使用itemList检查一个集合是否包含另一集合的至少一项。

intersection

对于很长的列表,从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