enumerate till 10 and reverse the output in swift

You can enumerate till 10 and reverse the output in Swift as follows:

main.swift
// Enumerate till 10
for number in 1...10 {
    print(number)
}

// Enumerate in reverse order
for number in (1...10).reversed() {
    print(number)
}
151 chars
10 lines

The first for-loop iterates from 1 to 10, printing each number along the way. The second for-loop uses the reversed() method to iterate in reverse order, starting from 10 and printing each number in reverse order until it reaches 1.

Note that the second loop creates a new reversed sequence, which can be memory-intensive for large input sizes. If performance is a concern, you might consider using stride(from:to:by:) or StrideThrough instead.

related categories

gistlibby LogSnag