Array+Extensions.swift 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. // Sources/SwiftProtobufPluginLibrary/Array+Extensions.swift - Additions to Arrays
  2. //
  3. // Copyright (c) 2014 - 2017 Apple Inc. and the project authors
  4. // Licensed under Apache License v2.0 with Runtime Library Exception
  5. //
  6. // See LICENSE.txt for license information:
  7. // https://github.com/apple/swift-protobuf/blob/main/LICENSE.txt
  8. //
  9. // -----------------------------------------------------------------------------
  10. import Foundation
  11. extension Array {
  12. /// Like map, but calls the transform with the index and value.
  13. ///
  14. /// NOTE: It would seem like doing:
  15. /// return self.enumerated().map {
  16. /// return try transform($0.index, $0.element)
  17. /// }
  18. /// would seem like a simple thing to avoid extension. However as of Xcode 8.3.2
  19. /// (Swift 3.1), building/running 5000000 interation test (macOS) of the differences
  20. /// are rather large -
  21. /// Release build:
  22. /// Using enumerated: 3.694987967
  23. /// Using enumeratedMap: 0.961241992
  24. /// Debug build:
  25. /// Using enumerated: 20.038512905
  26. /// Using enumeratedMap: 8.521299144
  27. func enumeratedMap<T>(_ transform: (Int, Element) throws -> T) rethrows -> [T] {
  28. var i: Int = -1
  29. return try map {
  30. i += 1
  31. return try transform(i, $0)
  32. }
  33. }
  34. }
  35. #if !swift(>=4.2)
  36. extension Array {
  37. func firstIndex(where predicate: (Element) throws -> Bool) rethrows -> Int? {
  38. var i = self.startIndex
  39. while i < self.endIndex {
  40. if try predicate(self[i]) {
  41. return i
  42. }
  43. self.formIndex(after: &i)
  44. }
  45. return nil
  46. }
  47. }
  48. #endif // !swift(>=4.2)