Xcode 9.4.1 Swift 4 - Comparing a non-primitive Se

2019-08-29 23:50发布

问题:

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.

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
}

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.

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

回答1:

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
}

For a very long list it might be more efficient to subtract the currently checked values from 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
}


标签: swift set