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
-
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]
- 热议问题