xcode的9.4.1夫特4 - 一个非原始集与包含诠释一个原始组(Xcode 9.4.1 Swi

2019-10-28 23:10发布

我难倒就如何处理这种情况下,我无法弄清楚如何检查listGroup的每个列表中的单个值返回true之前就存在,如果一个值从4名列表中的一个缺失的FUNC必须返回false。

ID - 对象:中等,名称:字符串,组:字符串通过粘贴将具有包含ID,名称组实施例通过内objList传递的对象的数据结构列表

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内objList穿过。 但是,如果从每个子集listGroups的值存在FUNC只能返回true。

所有4个子单个值必须存在,这样我才可以返回true,如果一个一个或多个缺少FUNC必须返回false

Answer 1:

创建一个SetiditemList ,并使用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

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 - Comparing a non-primitive Set to a primitive set containing Int
标签: swift set