# how to get all proper subsets of a set in swift

There are several ways to get all proper subsets of a given set in Swift. One simple way is to use recursion to generate all possible subsets. Here's an implementation:

```main.swift```func subsets(_ nums: [Int]) -> [[Int]] {
var res = [[Int]]()
var temp = [Int]()
helper(&res, &temp, nums.sorted(), 0)
return res
}

func helper(_ res: inout [[Int]], _ temp: inout [Int], _ nums: [Int], _ start: Int) {
if temp.count > 0 && temp.count < nums.count {
res.append(temp)
}
for i in start..<nums.count {
temp.append(nums[i])
helper(&res, &temp, nums, i + 1)
temp.removeLast()
}
}
```454 chars18 lines```

This function takes an array of integers as input, sorts it, and recursively generates all possible subsets of the array, skipping the empty set and the set containing all elements.

Another way to generate all subsets is to use bit manipulation to get the power set of the array. Here's an implementation:

```main.swift```func subsets(_ nums: [Int]) -> [[Int]] {
var res = [[Int]]()
let n = nums.count
for i in 0..<1<<n {
var temp = [Int]()
for j in 0..<n {
if i>>j & 1 == 1 {
temp.append(nums[j])
}
}
if temp.count > 0 && temp.count < n {
res.append(temp)
}
}
return res
}
```364 chars17 lines```

This function takes an array of integers as input, gets the length of the array, and uses bit manipulation to generate the power set of the array. It then filters out the empty set and the set containing all elements.

### related categories

gistlibby LogSnag