Filter and sort swift array

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

    Another way:

    let searchString = "p"
    let array = ["apple", "workshops", "shopping", "sports", "parties", "pantry", "pen", "xyzzy"]
    let result = array.filter{$0.containsString(searchString)}
        .map{($0.hasPrefix(searchString) ? 0 : 1, $0)}
        .sort{$0 < $1}
        .map{$1}
    print(result) //->["pantry", "parties", "pen", "apple", "shopping", "sports", "workshops"]
    

    (I don't know why, but my Xcode took huge time to compile these lines. Believe this compiles and runs as expected eventually.)

提交回复
热议问题