我想遍历 array
中的所有项目,然后更改所有字符串。然后我想用新字符串对数组进行排序。
更具体地说,我有一个数组 ["1,8", "3,5", "2,5", "4"] 并且想将逗号更改为点并排序为 [1.8, 3.5, 2.5, 4 ]
如何使用 map
和 sorted
实现这一点?
最佳答案
您可以使用 flatMap(_:)
with replacingOccurrences(of:with:)
在将字符串转换为数字时忽略 nil 结果,然后对结果数组进行排序。
let array = ["1,8", "3,5", "2,5", "4"]
let sortedArray = array.flatMap({ Double($0.replacingOccurrences(of: ",", with: ".")) }).sorted()
print(sortedArray) //[1.8, 2.5, 3.5, 4.0]
注意:如果您的 Swift 版本是 4.1 或更高版本,请使用 compactMap(_:)
因为 flatMap
在 Swift 4.1 中被弃用了。
let sortedArray = array.compactMap({ Double($0.replacingOccurrences(of: ",", with: ".")) }).sorted()
关于ios - 在 Swift 中一起使用 map 和 sorted 的最佳方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51875035/