斯威夫特:数组排序没有做正确 [英] Swift: sorting of array is not done correctly

查看:137
本文介绍了斯威夫特:数组排序没有做正确的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用这在斯威夫特的阵列组件进行排序:

  myArray的= myArray.sorted {$ 0.localizedCaseInsensitiveCompare($ 1)== NSComparisonResult.OrderedAscending}

然而,它给了我以下结果:

  [18C,18L,18R,22,24,27,36C,36L,36R,4,6,9]

是否有可能以正确的方式对其进行排序,即

  [4,6,9,18C,18L,18R,22,24,27,36C,36L,36R]


解决方案

您可以使用比较 .NumericSearch

  array.sortInPlace {$ 0.compare($ 1,选择:.NumericSearch)== .OrderedAscending}

 让数组2 = {的Array.sort $ 0.compare($ 1,选择:.NumericSearch)== .OrderedAscending}

I am using this to sort components in an array in Swift:

myArray = myArray.sorted { $0.localizedCaseInsensitiveCompare($1) == NSComparisonResult.OrderedAscending }

However, it gives me the following result:

[18C, 18L, 18R, 22, 24, 27, 36C, 36L, 36R, 4, 6, 9]

Is it possible to sort it the right way, i.e.

[4, 6, 9, 18C, 18L, 18R, 22, 24, 27, 36C, 36L, 36R]

解决方案

You can use compare with .NumericSearch:

array.sortInPlace { $0.compare($1, options: .NumericSearch) == .OrderedAscending }

or

let array2 = array.sort { $0.compare($1, options: .NumericSearch) == .OrderedAscending }

这篇关于斯威夫特:数组排序没有做正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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