how to get all permutations of a set in swift

Here's a simple recursive solution to get all permutations of a set in Swift:

main.swift
func permutations<T>(_ array: [T], _ length: Int? = nil, _ current: [T] = [], _ used: Set<Int> = .init()) -> [[T]] {
    let length = length ?? array.count
    if current.count == length {
        return [current]
    } else {
        var result: [[T]] = []
        for (i, elem) in array.enumerated() where !used.contains(i) {
            var nextUsed = used
            nextUsed.insert(i)
            result += permutations(array, length, current + [elem], nextUsed)
        }
        return result
    }
}
509 chars
15 lines

You can use this function like this:

main.swift
let set = [1, 2, 3]
let perms = permutations(set) // returns [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
128 chars
3 lines

gistlibby LogSnag