我想在 Pyramida 結構中添加一個 filter(_:) 方法。它應該接受一個引數,一個閉包:接受一個元素并回傳一個布林值,并回傳一個新的 Pyramida,其中包含閉包回傳 true 的任何元素,例如大于 10 的值。
當我使用與(在練習中)已經存在的 func 映射相同的代碼時,它的實作只列印出 [false, false, true],但不是高于 10 的值。
還嘗試按照開發人員檔案中所述的語法調整 func 過濾器,但是沒有進一步管理它,錯誤太多。
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))
uj5u.com熱心網友回復:
您必須添加此方法,如果 isIncluded 為真,則必須將新元素附加到陣列中。
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)
}
你也可以使用它。
public func filter(_ isIncluded: (Element) throws -> Bool) rethrows -> Pyramida <Element>{
return Pyramida(items: try items.filter(isIncluded))
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/415123.html
標籤:
