将 nil 排序到可选字符串数组的末尾

Joh*_*ery 2 arrays sorting optional swift

如果我有一个可选字符串数组,并且我想以 nils 开头的升序对其进行排序,我可以在一行中轻松完成:

["b", nil, "a"].sorted{ $0 ?? "" < $1 ?? "" } // [nil, "a", "b"]
Run Code Online (Sandbox Code Playgroud)

但是似乎没有任何类似的简单解决方案可以将 nil 排序到数组的末尾。使用大多数其他简单数据类型可以轻松完成,例如:

[2, nil, 1].sorted{ $0 ?? Int.max < $1 ?? Int.max } // [1, 2, nil]
Run Code Online (Sandbox Code Playgroud)

对于双打,您可以使用greatestFiniteMagnitude,对于日期,您可以使用distantFuture。是否有任何类型的字符串等价物,或任何其他简洁的方法来做到这一点,这样我就可以避免编写一堆凌乱的条件?

Mar*_*n R 5

您可以提供一个自定义比较器,它认为nil 大于任何非零值:

let array = ["b", nil, "a", nil]

let sortedArray = array.sorted { (lhs, rhs) -> Bool in
    switch (lhs, rhs) {
    case let(l?, r?): return l < r // Both lhs and rhs are not nil
    case (nil, _): return false    // Lhs is nil
    case (_?, nil): return true    // Lhs is not nil, rhs is nil
    }
}

print(sortedArray) // [Optional("a"), Optional("b"), nil, nil]
Run Code Online (Sandbox Code Playgroud)

这适用于任何可选的可比较元素数组,并避免使用“神奇的大”值。比较器可以实现为一个通用函数:

func compareOptionalsWithLargeNil<T: Comparable>(lhs: T?, rhs: T?) -> Bool {
    switch (lhs, rhs) {
    case let(l?, r?): return l < r // Both lhs and rhs are not nil
    case (nil, _): return false    // Lhs is nil
    case (_?, nil): return true    // Lhs is not nil, rhs is nil
    }
}

print(["b", nil, "a", nil].sorted(by: compareOptionalsWithLargeNil))
// [Optional("a"), Optional("b"), nil, nil]

print([2, nil, 1].sorted(by: compareOptionalsWithLargeNil))
// [Optional(1), Optional(2), nil]

print([3.0, nil, 1.0].sorted(by: compareOptionalsWithLargeNil))
// [Optional(1.0), Optional(3.0), nil]

print([Date(), nil, .distantPast, nil, .distantFuture].sorted(by: compareOptionalsWithLargeNil))
// [Optional(0000-12-30 00:00:00 +0000), Optional(2018-11-22 13:56:03 +0000),
//  Optional(4001-01-01 00:00:00 +0000), nil, nil]
Run Code Online (Sandbox Code Playgroud)