将nil排序到可选字符串数组的末尾 [英] Sort nil to the end of an array of optional strings

查看:106
本文介绍了将nil排序到可选字符串数组的末尾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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, "a"].sorted{ $0 ?? "" < $1 ?? "" } // [nil, "a", "b"]

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

But there doesn't seem to be any similarly easy solution to sort nils to the end of the array. It can be easily done with most other simple data types, for instance:

[2, nil, 1].sorted{ $0 ?? Int.max < $1 ?? Int.max } // [1, 2, nil]

对于双打,您可以使用greatestFiniteMagnitude进行相同的操作,对于日期,可以使用distantFuture.字符串是否有任何等效形式,或者有其他简洁的方式可以避免编写一堆乱七八糟的条件语句?

For doubles you can do the same with greatestFiniteMagnitude, for dates you can use distantFuture. Is there any kind of equivalent for strings, or any other concise way of doing this so I can avoid writing a bunch of messy conditionals?

推荐答案

您可以提供考虑nil的自定义比较器 大于任何非nil值:

You can provide a custom comparator which considers nil as larger than any non-nil value:

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]

这适用于任何可选的可比较元素数组,并避免了 不可思议的大"值的用法.比较器可以实现 作为通用函数:

This works with any array of optional comparable elements, and avoids the usage of "magical large" values. The comparator can be implemented as a generic function:

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]

这篇关于将nil排序到可选字符串数组的末尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆