sametbilgi
sametbilgi

Reputation: 602

What is the best way to use map and sorted together in Swift

I want to iterate all items in my array and then change all strings. Then I want to sort the array with the new strings.

More specifically I have an array ["1,8", "3,5", "2,5", "4"] and want to change commas to dot and sort like [1.8, 3.5, 2.5, 4]

How can I achieve this by using map and sorted?

Upvotes: 1

Views: 2063

Answers (2)

Mridul Gupta
Mridul Gupta

Reputation: 609

var array = ["1,8", "3,5", "2,5", "4"]
var sortedArray = array.map{Double($0.replacingOccurrences(of: ",", with: "."))!}.sorted(by: {$0 < $1})
print(sortedArray)

Upvotes: 2

Nirav D
Nirav D

Reputation: 72420

You can use flatMap(_:) with replacingOccurrences(of:with:) to ignore the nil result while converting string to number and then sort the result array.

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]

Note: If your Swift version is 4.1 or greater than use compactMap(_:) because flatMap is deprecated in Swift 4.1.

let sortedArray = array.compactMap({ Double($0.replacingOccurrences(of: ",", with: ".")) }).sorted()

Upvotes: 4

Related Questions