Filtering an Array

suggest change

You can use the filter(_:) method on SequenceType in order to create a new array containing the elements of the sequence that satisfy a given predicate, which can be provided as a closure.

For example, filtering even numbers from an [Int]:

let numbers = [22, 41, 23, 30]

let evenNumbers = numbers.filter { $0 % 2 == 0 }

print(evenNumbers)  // [22, 30]

Filtering a [Person], where their age is less than 30:

struct Person {
    var age : Int
}

let people = [Person(age: 22), Person(age: 41), Person(age: 23), Person(age: 30)]

let peopleYoungerThan30 = people.filter { $0.age < 30 }

print(peopleYoungerThan30) // [Person(age: 22), Person(age: 23)]

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents