0

I have a string array called prodIDArr having values like so...

["1","2","3","4","5","6","7","8","9","10"] 

But when I do something like so..

let maxVal = prodIDArr.max()

I get the value of maxVal as 9 and not 10.

What could be the reason for this...?

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382

2 Answers2

3

That is an array of strings, and those are compared lexicographically:

"1" < "10" < "2" < ... < "9" 

For example "10" < "2" because the initial characters already satisfy "1" < "2". (For the gory details, see for example What does it mean that string and character comparisons in Swift are not locale-sensitive?.)

Using an array of integers would be the best solution:

let prodIDArr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let maxId = prodIDArr.max()
print(maxId) // Optional(10)

If that is not possible then you can enforce a numeric comparison with

let prodIDArr = ["1","2","3","4","5","6","7","8","9","10"]
let maxId = prodIDArr.max(by: { $0.compare($1, options: .numeric) == .orderedAscending })
print(maxId) // Optional("10")
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
0

You can also map your original String Array to an Int Array

let prodIDArr = ["1","2","3","4","5","6","7","8","9","10"]
let prodNumArray = prodIDArr.map { input in Int(input)!} // or { Int($0)! }
print(prodNumArray.max()!)
claude31
  • 874
  • 6
  • 8