過濾陣列
可以使用 filter(_:)
方法上 SequenceType
以建立包含滿足給定謂詞序列,其可以作為一個被提供的元素的新陣列閉合 。
例如,從 [Int]
中過濾偶數:
let numbers = [22, 41, 23, 30]
let evenNumbers = numbers.filter { $0 % 2 == 0 }
print(evenNumbers) // [22, 30]
過濾 [Person]
,年齡小於 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)]