Swift对包含字符串和数字的数组进行排序

时间:2017-05-09 12:40:13

标签: arrays swift sorting

我有一个字符串数组,

Array.sorted { $0? < $1? }

我想将输出按升序排序,

SELECT @NetValue / (@DaysRemaining/365)

我尝试使用sorted命令,但遇到2位以上时不起作用,例如:100,101,200等。

@DaysRemaining

获得此功能的简单方法是什么?

1 个答案:

答案 0 :(得分:44)

编辑/更新: Xcode 10.2.x•Swift 5

您可以使用String method localizedStandardCompare

let array = [ "10", "1", "101", "NA", "100", "20", "210", "200", "NA", "7" ]
let sorted = array.sorted {$0.localizedStandardCompare($1) == .orderedAscending}

print(sorted) // ["1", "7", "10", "20", "100", "101", "200", "210", "NA", "NA"]

或在MutableCollection上使用方法sort(by:)

var array = [ "10", "1", "101", "NA", "100", "20", "210", "200", "NA", "7" ]
array.sort {$0.localizedStandardCompare($1) == .orderedAscending}

print(array) // ["1", "7", "10", "20", "100", "101", "200", "210", "NA", "NA"]

您还可以实现扩展Collection:

的自己的本地化标准排序方法
extension Collection where Element: StringProtocol {
    public func localizedStandardSorted(_ result: ComparisonResult) -> [Element] {
        return sorted { $0.localizedStandardCompare($1) == result }
    }
}
let array = [ "10", "1", "101", "NA", "100", "20", "210", "200", "NA", "7" ]
let sorted = array.localizedStandardSorted(.orderedAscending)

print(sorted) // ["1", "7", "10", "20", "100", "101", "200", "210", "NA", "NA"]

变异方法以及扩展MutableCollection:

extension MutableCollection where Element: StringProtocol, Self: RandomAccessCollection {
    public mutating func localizedStandardSort(_ result: ComparisonResult) {
        sort { $0.localizedStandardCompare($1) == result }
    }
}
var array = [ "10", "1", "101", "NA", "100", "20", "210", "200", "NA", "7" ]
array.localizedStandardSort(.orderedAscending)

print(array) // ["1", "7", "10", "20", "100", "101", "200", "210", "NA", "NA"]

如果需要以数字方式对数组进行排序,可以使用字符串比较方法将可选选项参数设置为.numeric

public extension Collection where Element: StringProtocol {
    func sortedNumerically(_ result: ComparisonResult) -> [Element] {
        return sorted { $0.compare($1, options: .numeric) == result }
    }
}
public extension MutableCollection where Element: StringProtocol, Self: RandomAccessCollection {
    mutating func sortNumerically(_ result: ComparisonResult) {
        sort { $0.compare($1, options: .numeric) == result }
    }
}
var numbers = ["1.5","0.5","1"]
let sorted = numbers.sortedNumerically(.orderedAscending)
print(sorted)  // ["0.5", "1", "1.5"]
print(numbers) // ["1.5","0.5","1"]
// mutating the original collection
numbers.sortNumerically(.orderedDescending)
print(numbers)  // "["1.5", "1", "0.5"]\n"