Search code examples
iosswiftfilterswift4

Filter and sort swift array of dictionaries


I have the following array:

let parent = [ ["Step":"S 3", "Desc":"Do third step" ],
               ["Step":"S 1", "Desc":"Do first step" ],
               ["Step":"S 2", "Desc":"Do second step" ],
                ["Step":"P 1", "Desc":"Some other thing" ] ]

How do I filter and sort the array(using filter and sort functions) in the least possible steps so that I get the following output string or label --

1.Do first step

2.Do second step

3.Do third step


Solution

  • let sorted = parent.filter({ ($0["Step"]?.hasPrefix("S"))! }).sorted { $0["Step"]! < $1["Step"]!}
    var prefix = 0
    let strings = sorted.reduce("") { (partial, next) -> String in
       prefix += 1
       return partial + "\(prefix)." + next["Desc"]! + "\n"
    }