Swift 中使用 localizedStandardCompare 对名称进行排序
在 Swift 中,可以使用字符串的'localizedStandardCompare'方法对名称进行排序。
例如,假设有一个数组'names'包含了一些名称:
let names = ['张三', '李四', '王五', '赵六', '孙七']
要对这些名称进行排序,可以使用'sorted(by:)'方法,并提供一个闭包作为比较器。在闭包中,可以使用'localizedStandardCompare'方法来对名称进行排序:
let sortedNames = names.sorted { $0.localizedStandardCompare($1) == .orderedAscending }
这将返回一个新的已排序的数组'sortedNames',其中的名称按照字母顺序进行排序。在这个例子中,'sortedNames'将是['孙七', '李四', '王五', '赵六', '张三']。
如果想要按照名称的反向顺序进行排序,则可以使用'.orderedDescending':
let sortedNamesDescending = names.sorted { $0.localizedStandardCompare($1) == .orderedDescending }
这将返回一个新的已排序的数组'sortedNamesDescending',其中的名称按照字母相反的顺序进行排序。在这个例子中,'sortedNamesDescending'将是['张三', '赵六', '王五', '李四', '孙七']。
原文地址: https://www.cveoy.top/t/topic/pf4h 著作权归作者所有。请勿转载和采集!