1
\$\begingroup\$

This method is an attempt at removing duplicates from arrays with scalability in mind in Swift 4 without the use of extensions. I am asking for any suggestions, criticisms, and/or observations.

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\$
  • \$\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\$ – Sᴀᴍ Onᴇᴌᴀ Nov 15 '18 at 19:16
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\$
  • \$\begingroup\$ In this case I'm not worried about order, thanks for the help. \$\endgroup\$ – bsod Nov 15 '18 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, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.