web-dev-qa-db-ja.com

Swift文字列と数字で配列をソート

文字列の配列があり、

let array = [ "10", "1", "101", "NA", "100", "20", "210", "200", "NA", "7" ]

出力を昇順に並べ替えたいのですが、

let sorted = [ "1", "7", "10", "20", "100", "101", "200", "210", "NA", "NA" ]

ソートされたコマンドを使用しようとしましたが、2桁を超える場合は機能しません(例:100、101、200など).

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

これを取得する簡単な方法は何ですか?

18
dacscan3669

編集/更新:Xcode 10.2.x•Swift 5

Stringメソッドの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"]
_

コレクションを拡張する独自のローカライズされた標準の並べ替えメソッドを実装することもできます。

_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"
_
51
Leo Dabus