Filter and sort swift array

后端 未结 3 2065
隐瞒了意图╮
隐瞒了意图╮ 2021-02-13 02:28

I have a swift array which I want to filter, here is the array

let array = [apple,workshops,shopping,sports,parties,pantry,pen] 

I want to filt

3条回答
  •  爱一瞬间的悲伤
    2021-02-13 02:43

    Try this. Firstly, it filters the array to remove those elements that do not contain the search string, then uses a custom sort to prefer items that start with the search string. In general, use the Cartesian approach of splitting a problem into smaller sub-problems, rather than try to solve it all in one step.

    let searchString = "p"
    let array = ["apple", "workshops", "shopping", "sports", "parties", "pantry", "pen", "xyzzy"]
    
    let filteredArray = array.filter({ $0.contains(searchString) })
    filteredArray // drops xyzzy
    
    let sortedArray = filteredArray.sorted(isOrderedBefore:  {
        switch ($0.hasPrefix(searchString), $1.hasPrefix(searchString)) {
        case (true, true):
            return $0 < $1
        case (true, false):
            return true
        case (false, true):
            return false
        case (false, false):
            return $0 < $1
        }
    
    })
    sortedArray // "pantry", "parties", "pen", "apple", "shopping", "sports", "workshops"] as required
    

提交回复
热议问题