Swift - How to check all sub sets and return true if each item is present in list

 ̄綄美尐妖づ 提交于 2019-12-11 10:53:17

问题


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
}


来源:https://stackoverflow.com/questions/53637597/swift-how-to-check-all-sub-sets-and-return-true-if-each-item-is-present-in-lis

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!