Array+Extension.swift 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. //
  2. // Array+Extension.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 16/08/22.
  6. // Copyright © 2022 Marino Faggiana. All rights reserved.
  7. //
  8. // Author Marino Faggiana <marino.faggiana@nextcloud.com>
  9. // Found in Internet
  10. //
  11. // This program is free software: you can redistribute it and/or modify
  12. // it under the terms of the GNU General Public License as published by
  13. // the Free Software Foundation, either version 3 of the License, or
  14. // (at your option) any later version.
  15. //
  16. // This program is distributed in the hope that it will be useful,
  17. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. // GNU General Public License for more details.
  20. //
  21. // You should have received a copy of the GNU General Public License
  22. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  23. //
  24. import Foundation
  25. // https://stackoverflow.com/questions/33861036/unique-objects-inside-a-array-swift/45023247#45023247
  26. extension Array {
  27. func unique<T: Hashable>(map: ((Element) -> (T))) -> [Element] {
  28. var set = Set<T>() // the unique list kept in a Set for fast retrieval
  29. var arrayOrdered = [Element]() // keeping the unique list of elements but ordered
  30. for value in self where !set.contains(map(value)) {
  31. set.insert(map(value))
  32. arrayOrdered.append(value)
  33. }
  34. return arrayOrdered
  35. }
  36. }