Sort nil to the end of an array of optional strings

前端 未结 3 1777
不思量自难忘°
不思量自难忘° 2021-01-14 22:08

If I have an array of optional strings, and I want to sort it in ascending order with nils at the beginning, I can do it easily in a single line:

[\"b\", nil         


        
3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-14 22:45

    Your example with Int gives a clue. If we had a max string value, we could plug that in.

    This works for strings that contain only alphabetic characters:

    let maxString = "~"
    ["b", nil, "a"].sorted{ $0 ?? maxString < $1 ?? maxString }
    

    Or simply:

    ["b", nil, "a"].sorted{ $0 ?? "~" < $1 ?? "~" }
    

提交回复
热议问题