Need to create an array of sets swift

1.5k views Asked by At

I'm brand new to Swift, and it's been awhile since I've done any programming at all so please forgive me. I need some help on how to create an empty array that would contain a set of numbers.

What I'm trying to do is read two sets of numbers in from two different data files, and place them into two different data structures - in this case - arrays. I then want to loop through the array and determine if one group of numbers is a subset of the other. I have created the following code in the swift playground, and tested it and I know it can be done using pre-defined values in the code.

However, I can't seem to find anywhere online how to create an array of sets. I find all sorts of links that say when to use an array rather than a set and vice versa. When I try to declare an empty Array of type Set it gives me an error. I would appreciate anyone pointing me in the right direction. Here is the code that I typed into the playground that works.

var a: Set = [1,2]
var b: Set = [1,3]
var c: Set = [1,4]

var aa: Set = [1,4,23,29,50]
var bb: Set = [1,3,45,47,65]
var cc: Set = [7,9,24,45,55]

let combiArray = [a, b, c]
let resultsArray = [aa, bb, cc]

for i in 0...2 {
print (resultsArray[i], 
       combiArray[i], 
       combiArray[i].isSubset(of: resultsArray[i]))
}
1

There are 1 answers

0
Alexander On

Set is a generic type. When you say var a: Set = [1, 2], the compiler infers the necessary generic type parameter for you, making it equivalent to var a: Set<Int> = [1, 2]

To make an empty Array of Sets, you have to explicitly state what kind of Set you want, because the compiler can't infer it from the Set's contents. You're looking to make an empty Array<Set<Int>>, a.k.a. [Set<Int>].

Either:

let arrayOfSets: [Set<Int>] = []

or:

let arrayOfSets = [Set<Int>]() // preferred

Here's that reflected in your example:

let combiArray: [Set<Int>] = [ // TODO: What the heck is a "combi"?
    [1, 2],
    [1, 3],
    [1, 4],
]
let results: [Set<Int>] = [
    [1, 4, 23, 29, 50],
    [1, 3, 45, 47, 65],
    [7, 9, 24, 45, 55],
]

for (combi, result) in zip(combiArray, results) {
    print("\(combi) \(combi.isSubset(of: result) ? "is" : "is not") a subset of \(result).")
}