过滤数组

可以使用 filter(_:) 方法上 SequenceType 以创建包含满足给定谓词序列,其可以作为一个被提供的元素的新阵列闭合

例如,从 [Int] 中过滤偶数:

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

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

print(evenNumbers)  // [22, 30]

过滤 [Person],年龄小于 30 岁:

 placeholderCopystruct 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)]