You exit the function early by calling return when the first pair is found. Instead, you should return an array of tuples containing the pairs, iterate over all pairs and add the ones satisfying the requirements to the return array.
func checkPairs(in numbers: [Int], forSum target: Int) -> [(Int,Int)] {
var pairs = [(Int,Int)]()
for (i, x) in numbers.enumerated() {
for y in numbers[i+1 ..< numbers.count] {
if x + y == target {
pairs.append((x,y))
}
}
}
return pairs
}
print(checkPairs(in: [1, 2, 4, 4, 7, 5, 3], forSum: 8))
Output:
[(1, 7), (4, 4), (5, 3)]
If you're looking for unique pairs, you can define a custom type holding the pair of numbers and return a Set instead of an Array (the custom type is needed, since you cannot make a Tuple conform to Hashable, which is needed to be able to add elements to a Set).
struct Pair: Hashable {
let smaller:Int
let bigger:Int
init(_ a:Int, _ b:Int) {
if a < b {
smaller = a
bigger = b
} else {
smaller = b
bigger = a
}
}
}
extension Pair: CustomStringConvertible {
var description:String {
return "\((smaller,bigger))"
}
}
func checkPairs(in numbers: [Int], forSum target: Int) -> Set<Pair> {
var pairs = Set<Pair>()
for (i, x) in numbers.enumerated() {
for y in numbers[i+1 ..< numbers.count] {
if x + y == target {
pairs.insert(Pair(x,y))
}
}
}
return pairs
}
print(checkPairs(in: [1, 2, 4, 4, 7, 5, 3], forSum: 8))
print(checkPairs(in: [1, 2, 4, 4, 7, 5, 3, 4, 1], forSum: 8))
Output:
[(4, 4), (3, 5), (1, 7)]
[(4, 4), (3, 5), (1, 7)]