O'Reilly logo

Swift Functional Programming - Second Edition by Dr. Fatih Nayebi

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Removing duplicates in an array

We can use reduce to remove duplicate elements in an array as follows:

let arrWithDuplicates = [1, 1, 2, 3, 3, 4, 4, 5, 6, 7] let arrWithoutDuplicates = arrWithDuplicates.reduce([]) {     (a: [Int], b: Int) -> [Int] in     if a.contains(b) {         return a     } else {         return a + [b]     } } print(arrWithoutDuplicates) 

The result will be [1, 2, 3, 4, 5, 6, 7], as expected.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required