Swift 3.1 has solved this problem with drop(while:)
and prefix(while:)
struct Person {
let isMale: Bool
let name: String
}
let people = [Person(isMale: true, name: "Bill"),
Person(isMale: false, name: "Jane"),
Person(isMale: true, name: "José"),
Person(isMale: false, name: "Sarah"),
Person(isMale: true, name: "Steve"),
Person(isMale: true, name: "Tony")]
func trimMen(people: [Person]) -> [Person] {
let removedPrefixMen = people.drop { $0.isMale }
let removedSuffixMen = removedPrefixMen.reversed().drop { $0.isMale }
return removedSuffixMen.reversed()
}
// [{isMale false, name "Jane"}, {isMale true, name "José"}, {isMale false, name "Sarah"}]
Also in Swift 3.1, concrete constrained extensions, means I can do this…
extension Array where Element == Person {
func trimMen() -> [Element] {
let removedPrefixMen = drop{ $0.isMale }
let removedSuffixMen = removedPrefixMen.reversed().drop{ $0.isMale }
return removedSuffixMen.reversed()
}
}
people.trimMen()