如何用函数式编程将指定字典转换为IndexPath数组?
Got it! Let's refactor that loop into clean, idiomatic functional Swift code. We'll leverage flatMap, enumerated(), and optional chaining to match the behavior of your original loop while keeping things concise.
First, let's recap your starting data:
let sections = ["A": ["Item1", "Item2", "Item3", "Item4"], "B": ["Item1", "Item2", "Item3", "Item4"]] let sectionsKeys = Array(sections.keys).sorted()
Option 1: Concise Safe Implementation (Matches Your Guard Logic)
This version replicates the safety of your original guard statement (skipping sections with missing items) while using functional patterns:
let indexPaths = sectionsKeys.enumerated().flatMap { sectionPos, key in // Use optional chaining to handle missing items, return empty array if nil sections[key]?.enumerated().map { itemPos, _ in IndexPath(row: itemPos, section: sectionPos) } ?? [] }
Option 2: Explicit Safe Version (More Verbose, Clearer Intent)
If you prefer more explicit handling of the optional items (mirroring your guard clause directly), you can use compactMap first to filter out invalid sections, then flatten the result:
let indexPaths = sectionsKeys.enumerated() .compactMap { sectionPos, key -> [IndexPath]? in guard let items = sections[key] else { return nil } return items.enumerated().map { itemPos, _ in IndexPath(row: itemPos, section: sectionPos) } } .flatMap { $0 }
How This Works
enumerated()attaches the position (section index) to each key in your sortedsectionsKeysarrayflatMaptakes the array of IndexPaths generated for each valid section and flattens them into a single, flat array ofIndexPathobjects- Optional chaining (
sections[key]?) ensures we only process sections that have a valid array of items, just like your original guard statement
This approach is declarative—you're describing what you want to produce (a list of IndexPaths for every item in sorted sections) rather than writing step-by-step loop instructions.
内容的提问来源于stack exchange,提问作者Oleg Gordiichuk

