1
\$\begingroup\$

This method is an attempt at removing duplicates from arrays without the use of extensions.

func arrayWithDuplicatesRemoved<T: Equatable>(from array: [T]) -> [T] {
    var results = [T]()
    return array.compactMap { (element) -> T? in
        if results.contains(element) {
            return nil
        } else {
            results.append(element)
            return element
        }
    }
}

let dirty = ["apple", "kiwi", "grapefruit", "kiwi", "kiwi", "strawberry", "watermelon", "apple", "banana"]
let clean = arrayWithDuplicatesRemoved(from: dirty)
print(clean) // ["apple", "kiwi", "grapes", "strawberry", "watermelon", "banana"]
\$\endgroup\$
1
  • \$\begingroup\$ Welcome to Code Review! Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see what you may and may not do after receiving answers. \$\endgroup\$ Commented Nov 15, 2018 at 19:16

2 Answers 2

0
\$\begingroup\$

Your algorithm is O(n^2) so not very scalable... The immediate improvement I can think of is to use a Set for results (which means making T Hashable).

If you aren't worried about position, then just create a Set from an array and you are done.

\$\endgroup\$
1
  • \$\begingroup\$ In this case I'm not worried about order, thanks for the help. \$\endgroup\$
    – user184635
    Commented Nov 15, 2018 at 18:55
0
\$\begingroup\$

UPDATE

The original was not the most scalable; nesting how I did meant that the square of the size of the argument is how performance is measured (thanks to Daniel T. for pointing that out). This is much more scalable as performance is not entirely linear but much closer than before.

func ArrayWithDuplicatesRemovedFrom<T: Hashable>(array: [T]) -> [T] {
    return Array(Set(array))
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.