Here's a recursive function in Swift to get all combinations of a given set of elements:
main.swift786 chars15 lines
This function takes an array of elements and the number of elements to choose (the size of combinations). The function first checks for edge cases - if the choose size is zero, return an empty array, and for the base case where the choose size is one, it returns each element as an array.
For the other cases, the function iterates over each element of the array and uses recursion to get all combinations from the remaining elements with one less choose size. The subcombinations are then concatenated with the current element to get complete combinations.
Here's an example usage:
main.swift166 chars5 lines
gistlibby LogSnag