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"]
asked Nov 14, 2018 at 1:07
\$\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

1
\$\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.

answered Nov 15, 2018 at 18:18
\$\endgroup\$
1
  • \$\begingroup\$ In this case I'm not worried about order, thanks for the help. \$\endgroup\$ 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))
}
answered Nov 15, 2018 at 19:20
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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