我已經閱讀了有關在 swift 中過濾嵌套陣列的多個討論,但是它們都回傳父物件。
讓我們有這些簡單的資料:
struct MenuSection: Identifiable {
let id: id
var name: String
var menuRows: [MenuRow]
}
struct MenuRow: Identifiable, Hashable {
let id: id
var name: String
}
private let menuSections: [MenuSection] = [
MenuSection(id: 0, name: "Menu Group 1", menuRows: [
MenuRow(id: 0, name: "Menu 1")
]),
MenuSection(id: 1, name: "Menu Group 2", menuRows: [
MenuRow(id: 1, name: "Menu 2"),
MenuRow(id: 2, name: "Menu 3")
])
]
我的目標是獲取帶有 id 的 MenuRow。
所以,我創建了這個函式,它可以作業:
func getMenuRowWithId(menuRowId: id) -> MenuRow? {
for menuSection in menuSections {
for menuRow in menuSection.menuRows {
if menuRow.id == menuRowId {
return menuRow
}
}
}
return nil
}
但是,我想做一些更迅速(也許更有效率)的事情。
我試過類似的東西:
var filtered = menuSections.filter { $0.menuRows.filter { $0.id == 1 }.count != 0 }
但它回傳包含正確 MenuRow 的 MenuSection。=> 我只想要 menuRow。
我已經嘗試了很多東西,比如在過濾之前使用 compactMap/flatMap 來展平陣列。沒門。
如何瀏覽 menuSections 并僅獲得正確的 menuRow ?謝謝
uj5u.com熱心網友回復:
您可以flatMap先使用獲取一個陣列中的所有 MenuRow 物件,然后使用在該陣列中找到正確的物件first(where:)
let menuRow = menuSections.flatMap(\.menuRows).first(where: { $0.id == 1 })
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/530036.html
標籤:迅速筛选关闭
上一篇:從0到1搭建redis6.0.7
