combinations(ofCount:)

Returns a collection of combinations of this collection’s elements, with each combination having the specified number of elements.

Combinations.swift:295
func combinations(ofCount k: Int) -> CombinationsSequence<Self>

Parameters

k

The number of elements to include in each combination.

This example prints the different combinations of three from an array of four colors:

let colors = ["fuchsia", "cyan", "mauve", "magenta"]
for combo in colors.combinations(ofCount: 3) {
    print(combo.joined(separator: ", "))
}
// fuchsia, cyan, mauve
// fuchsia, cyan, magenta
// fuchsia, mauve, magenta
// cyan, mauve, magenta

The returned collection presents combinations in a consistent order, where the indices in each combination are in ascending lexicographical order. That is, in the example above, the combinations in order are the elements at [0, 1, 2], [0, 1, 3], [0, 2, 3], and finally [1, 2, 3].

If k is zero, the resulting sequence has exactly one element, an empty array. If k is greater than the number of elements in this sequence, the resulting sequence has no elements.