Skip to content

Instantly share code, notes, and snippets.

@islandjoe
Created May 31, 2018 13:57
Show Gist options
  • Save islandjoe/ba9a69b5d7bb99a474377cec835749ee to your computer and use it in GitHub Desktop.
Save islandjoe/ba9a69b5d7bb99a474377cec835749ee to your computer and use it in GitHub Desktop.
Filtering in Swift
let numbers = [1, 2, 3, 4, 5, 6, 7, 8]

Method 1

func isEven(x: Int) -> Bool {
  return x % 2 == 0
}

let evenNumbers = numbers.filter( isEven )
//-> [2, 4, 6, 8]

Method 2

let evenNumbers = numbers.filter() { (x)-> Bool in
  return x % 2 == 0
}
//-> [2, 4, 6, 8]

Method 3

let oddNumbers = numbers.filter { !isEven(x: $0) }
//-> [1, 3, 5, 7]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment