Home > Software design >  Print numbered list in swift
Print numbered list in swift

Time:10-21

I am trying to print out a set of students in a class in a numbered list.

Here's the code I have

var spanish101: Set = ["Angela", "Declan", "Aldany", "Alex", "Sonny", "Alif", "Skyla"]
var german101: Set = ["Angela", "Alex", "Declan", "Kenny", "Cynara", "Adam"]
var advancedCalculus: Set = ["Cynara", "Gabby", "Angela", "Samantha", "Ana", "Aldany", "Galina", "Jasmine"]
var artHistory: Set = ["Samantha", "Vanessa", "Aldrian", "Cynara", "Kenny", "Declan", "Skyla"]
var englishLiterature: Set = ["Gabby", "Jasmine", "Alex", "Alif", "Aldrian", "Adam", "Angela"]
var computerScience: Set = ["Galina", "Kenny", "Sonny", "Alex", "Skyla"]
 
var allStudents: Set = spanish101.union(german101).union(advancedCalculus).union(artHistory).union(englishLiterature).union(computerScience)


for students in allStudents
{
  print(students)
}

I've tried doing print(students.count, students), but that just prints out random numbers.

Unsure of why and where those numbers come from.
I've tried making a nested loop with for count in 1..<students.count , but that made the list print out 16 times.

I want the output to look like

1 studentName
2 studentName
3 studentName
4 studentName
...
16 studentName

CodePudding user response:

You could use:

for anEnumerated in allStudents.enumerated() {
    print("\(anEnumerated.0) - \(anEnumerated.1)")
}

Or

for (anOffset, aStudent) in allStudents.enumerated() {
    print("\(anOffset) - \(aStudent)")
}

If you want to start at 1 instead of 0, simply add 1: (anOffset 1) or \(anEnumerated.0 1)

But note that allStudents is a Set, so there is no guaranteed order on the enumeration.

You could use an Array to sort allStudents or maybe a OrderedSet from Swift-Collections.

CodePudding user response:

If you need sorting, then try using this solution:

allStudents
    .sorted(by: { $0 < $1 }) // Sorting
    .enumerated() // Numbering
    .forEach { // Cycle
        print("\($0   1) \($1)")
    }
  • Related