Sort nil to the end of an array of optional strings

前端 未结 3 1779
不思量自难忘°
不思量自难忘° 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条回答
  •  逝去的感伤
    2021-01-14 22:49

    One nil is indistinguishable from another. So if you have a working solution that happens to sort as you desire except that nil entries wind up at the start, use it and then remove the nil entries and append the same number of nil entries to the end.

    Example:

        var arr : [String?] = [nil, "b", nil, "a", nil]
        arr = arr.sorted{ $0 ?? "" < $1 ?? "" }
        if let ix = arr.firstIndex(where: {$0 != nil}) {
            arr = arr.suffix(from: ix) + Array(repeating: nil, count: ix)
        }
        // [Optional("a"), Optional("b"), nil, nil, nil]
    

自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题