Filter and sort swift array

后端 未结 3 2057
隐瞒了意图╮
隐瞒了意图╮ 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:40

    You can just write

     let result = words
        .filter { $0.contains(keyword) }
        .sorted { ($0.hasPrefix(keyword) ? 0 : 1) < ($1.hasPrefix(keyword) ? 0 : 1) }
    

    Example

    let words = ["apple", "workshops", "shopping", "sports", "parties", "pantry", "pen", "cat", "house"]
    let keyword = "p"
    let result = words
        .filter { $0.contains(keyword) }
        .sorted { ($0.hasPrefix(keyword) ? 0 : 1) < ($1.hasPrefix(keyword) ? 0 : 1) }
    
    // ["pen", "pantry", "parties", "apple", "workshops", "shopping", "sports"]
    

提交回复
热议问题