Search code examples
arraysswiftnestedset

How to extract multiple sets within a single set to become their own individual array in Swift?


let groupA : Set<Int> = [1111,2000]
let groupB : Set<Int> = [221,122]
let groupC : Set<Int> = [300,12,23,232] 


StudentGroups = [groupA, groupB, groupC]

Say that I can't access the declared sets above, I'm trying to find a solution to extract out each sets inside StudentGroups to become their new own array.

For example: The expected extracted arrays from studentGroups should be:

groupA = [1111,2000]
groupB = [221,122]
groupC = [300,12,23, 232] 

This is what I did to test my progress:

for idx in StudentGroups.indices {
   let elem = StudentGroups[idx]
    print(elem)

//This will return  [1111,2000]
//                  [221,122]
//                  [300,12,23,232]

}
        

At the moment, it's only iterating through the sets. Unfortunately, I'm a bit clueless on how to proceed from here


Solution

  • try something like this:

    let groupA : Set<Int> = [1111,2000]
    let groupB : Set<Int> = [221,122]
    let groupC : Set<Int> = [300,12,23,232]
    
    let studentGroups = [groupA, groupB, groupC]
    print("---> studentGroups: \(studentGroups)")
    
    for idx in studentGroups.indices {
        let arr = Array(studentGroups[idx])
        print("\n---> arr \(idx): \(arr)")
        for i in arr.indices {
            print("     ---> element \(i) of arr \(idx): \(arr[i])")
        }
    }
    
            
    

    ...a solution to extract out each sets inside StudentGroups to become their new own array..., try this, to transform an array of Sets into an array of arrays:

    var newArr: [[Int]] = studentGroups.map{ Array($0) }
    
    print("\n---> newArr: \(newArr)")
    print("\n---> newArr[0][0]: \(newArr[0][0])")