Advertisement
Guest User

Untitled

a guest
Jun 26th, 2017
52
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.90 KB | None | 0 0
  1. import Dispatch
  2.  
  3. /// Dispatch options for `forEach` loops
  4. public enum ForEachClosureDispatch {
  5. case sequential
  6. case concurrent
  7. }
  8.  
  9. extension Sequence {
  10. /// Calls the given closure on each element in the sequence in the same order
  11. /// as a `for`-`in` loop.
  12. ///
  13. /// The two loops in the following example produce the same output:
  14. ///
  15. /// let numberWords = ["one", "two", "three"]
  16. /// for word in numberWords {
  17. /// print(word)
  18. /// }
  19. /// // Prints "one"
  20. /// // Prints "two"
  21. /// // Prints "three"
  22. ///
  23. /// numberWords.forEach { word in
  24. /// print(word)
  25. /// }
  26. /// // Same as above
  27. ///
  28. /// Using the `forEach` method is distinct from a `for`-`in` loop in two
  29. /// important ways:
  30. ///
  31. /// 1. You cannot use a `break` or `continue` statement to exit the current
  32. /// call of the `body` closure or skip subsequent calls.
  33. /// 2. Using the `return` statement in the `body` closure will exit only from
  34. /// the current call to `body`, not from any outer scope, and won't skip
  35. /// subsequent calls.
  36. ///
  37. /// - Parameter approach: a flag that controls whether the
  38. /// body should be dispatched asynchronously or performed sequentially
  39. /// - Parameter body: A closure that takes an element of the
  40. /// sequence as a parameter.
  41. @_inlineable
  42. public func forEach(
  43. _ approach: ForEachClosureDispatch = .sequential,
  44. _ body: @escaping (Element) throws -> Void
  45. ) rethrows {
  46. for element in self {
  47. switch approach {
  48. case .sequential:
  49. try body(element)
  50. case .concurrent:
  51. DispatchQueue.global().async {
  52. do {
  53. try body(element)
  54. } catch { fatalError("\(error)") }
  55. }
  56. }
  57. }
  58. }
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement