Swift - 如果每个项目都存在于列表中,如何检查所有子集并返回 true [英] Swift - How to check all sub sets and return true if each item is present in list
问题描述
我需要一种方法来检查集合中的集合,其中每个子集必须在返回 true 之前出现在列表中.
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.
推荐答案
Swift 4.2
您应该检查 listGroups
的每个 list
是否包含来自 numbers
数组的至少一个 Int
.如果不是,则返回 false
.如果是,则返回 true
.为此,您可以使用 allSatisfy
方法
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) }
}
旧版本
对于旧版本的 Swift,您可以为每个循环创建类似的循环,但只是在多行上
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 - 如果每个项目都存在于列表中,如何检查所有子集并返回 true的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!