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...?

7
  • 6
    Because that are strings, not numbers. Commented May 11, 2018 at 7:50
  • But @Martin R how did it then consider the values till 9 Commented May 11, 2018 at 7:51
  • Strings are compared lexicographically: "1" < "10" < "2" < ... < "9" Commented May 11, 2018 at 7:53
  • I'm sorry @MartinR But what does lexicographically mean..? Commented May 11, 2018 at 7:53
  • It's the order that elements (for example words) would appear in a lexicon en.wikipedia.org/wiki/Lexicographical_order Commented May 11, 2018 at 7:59

2 Answers 2

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")
Sign up to request clarification or add additional context in comments.

Comments

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()!)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.