How to add filter(_:) method to generic structure in Swift?
I want to add a filter(_:) method to Pyramida structure. It should take a single argument, a closure that: takes an Element and returns a Bool, and return a new Pyramida that contains any elements for which the closure returns true, e.g. values higher than 10.
When I used the same code as per (within exercise) already existent func map also for func filter, its implementation prints out just [false, false, true], however not the values above 10.
Also tried to adjust the func filter as per syntax stated within Developer Documentation, however did not manage it further, too many errors.
struct Pyramida<Element> {
var items = [Element]()
mutating func push(_ newItem: Element) {
items.append(newItem)
}
mutating func pop() -> Element? {
guard !items.isEmpty else {return nil}
return items.removeLast()
}
func map<U>(_ txform: (Element) -> U) -> Pyramida<U> {
var mappedItems = [U]()
for item in items {
mappedItems.append(txform(item))
}
return Pyramida<U>(items: mappedItems)
}
func filter(_ isIncluded: (Element) -> Bool) -> Pyramida<[Int]> {
var filteredItems = [Int]()
for item in items {
if item > 10 {
filteredItems.append(filteredItems(item))
return Pyramida(items: filteredItems)
}
}
}
}
var ints = Pyramida<Int>()
ints.push(2)
ints.push(4)
ints.push(11)
var tripled = ints.map{ 3 * $0 }
print(String(describing: tripled.items))
var aboveTen = ints.filter{ 10 < $0} // code func map<U> for filter<U>
print(String(describing: aboveTen.items))
Solution 1:
you have to add this method and if the isIncluded is true you have to append the new element in your array.
func filter(_ isIncluded: (Element) throws -> Bool) rethrows -> Pyramida<Element> {
var newElements: [Element] = []
for number in items where try isIncluded(number) {
newElements.append(number)
}
return Pyramida(items: newElements)
}
and you also can use this.
public func filter(_ isIncluded: (Element) throws -> Bool) rethrows -> Pyramida <Element>{
return Pyramida(items: try items.filter(isIncluded))
}