Sha*_*ane 10 arrays sorting localization case-sensitive swift
我想使用另一种比较方法(如localizedCompare,caseInsensitiveCompare或localizedCaseInsensitiveCompare)对我的swift struct数组进行排序.swift标准字符串数组排序函数在小写字母之前排序所有大写字母.这是我的代码:
import Foundation
struct DataStruct {
struct Item {
let title: String
let number: Int
}
static var items = [
Item(title: "apple", number: 30),
Item(title: "Berry", number: 9),
Item(title: "apple", number: 18)]
}
class DataFunctions {
func sortItemsArrayTitle() {
DataStruct.items.sort { $0.title < $1.title }
}
}
Run Code Online (Sandbox Code Playgroud)
一旦调用,上面的代码就会产生[Berry,apple,apple].不能接受的.有什么建议?
Leo*_*bus 23
您可以通过比较标题lowercaseString轻松解决它,如下所示:
DataStruct.items.sort { $0.title.lowercaseString < $1.title.lowercaseString }
Run Code Online (Sandbox Code Playgroud)
使用localizedCompare它应该如下所示:
DataStruct.items.sort { $0.title.localizedCompare($1.title) == .OrderedAscending }
Run Code Online (Sandbox Code Playgroud)