-2

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]))
}
  • 4
    *"When I try to declare an empty Array of type Set ...”* – please show your attempt – *”... it gives me an error"* – please quote the exact error message. – Martin R Oct 05 '18 at 19:37
  • You should avoid calling variables along the lines of `fooArray`. It's better to just say `foos`, or something else that provides more information about the data. The fact that it's an array is the most obvious part of it, there's no need for it to be written in the name. – Alexander Oct 05 '18 at 19:39
  • Do you mean this `var setArray: [Set] = []` doesn't work? – Cristik Oct 05 '18 at 19:40
  • thank you for the feedback - I tried the example below and it worked! appreciate it very much - thanks again! – Mark Allen Oct 05 '18 at 21:14

1 Answers1

2

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).")
}
Alexander
  • 59,041
  • 12
  • 98
  • 151