Swift - How to check all sub sets and return true

2019-08-06 05:00发布

问题:

I require help in an approach to check through sets within a set where each sub-set must be present in the list before returning true.

init(){ 
    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]

    listGroups = [list1,list2,list3,list4] 
}

func checklist(_ list: [Numbers]) -> Bool { 
    //I want to check that each sub set(list1-list4) elements exist 
    //E.G. if list contains 2, 3, 7, 8 it will return true 
    //and if list contain 1, 4, 7, freturn false as it doesn't contain a  
    //number from each set 
} 

I dont necessarily want it done for me but an explanation on how to approach and why you suggest this approach.

I've kept the code example simple but if you need more just let me know.

回答1:

Swift 4.2

You should check if each list of listGroups contains at least one Int from numbers array. If doesn't, return false. If does, return true. For this you can use allSatisfy method

func checklist(_ numbers: [Int]) -> Bool {
    return listGroups.allSatisfy { $0.contains(where: numbers.contains) }
}

Older versions

For older versions of Swift you can create for each loop which does the similar, but just on multiple lines

func checklist(_ numbers: [Int]) -> Bool {

    for list in listGroups {
        if !list.contains(where: numbers.contains) {
            return false
        }
    }
    return true
}


标签: swift set