Skip to content

Instantly share code, notes, and snippets.

@bestiosdeveloper
Created May 19, 2020 19:48
Show Gist options
  • Save bestiosdeveloper/fd0cc1d85a566f5360e16c48670a0aba to your computer and use it in GitHub Desktop.
Save bestiosdeveloper/fd0cc1d85a566f5360e16c48670a0aba to your computer and use it in GitHub Desktop.
var numbers = Array(1...15)
// Find the indices of all the even numbers
let indicesOfEvens = numbers.subranges(where: { $0.isMultiple(of: 2) })
// Perform an operation with just the even numbers
let sumOfEvens = numbers[indicesOfEvens].reduce(0, +)
// sumOfEvens == 56
// You can gather the even numbers at the beginning
let rangeOfEvens = numbers.moveSubranges(indicesOfEvens, to: numbers.startIndex)
// numbers == [2, 4, 6, 8, 10, 12, 14, 1, 3, 5, 7, 9, 11, 13, 15]
// numbers[rangeOfEvens] == [2, 4, 6, 8, 10, 12, 14]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment