8

in this example:

var str1 = "hello"
var str2 = "Hello"

if str1 < str2 { print("hello is less than Hello")}
else {print("hello is more than Hello")}

on what basis it is found that str1 is greater than str2?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
KawaiKx
  • 9,558
  • 19
  • 72
  • 111
  • 2
    Related: [What does it mean that string and character comparisons in Swift are not locale-sensitive?](http://stackoverflow.com/questions/25713975/what-does-it-mean-that-string-and-character-comparisons-in-swift-are-not-locale) – Martin R Aug 12 '16 at 04:49
  • isn't it really obvious that as `H` has ascii decimal value `72` and `h` has the ascii decimal value `104`. So as like `strcmp` in **C** on the first index `h` is greater than `H` which why the outcome is so. – Ratul Sharker Apr 17 '18 at 20:38

4 Answers4

12

Swift strings are compared according to the Unicode Collation Algorithm, which means that (effectively),

In your example, "hello" and "Hello" have the Unicode values

hello: U+0068, U+0065, U+006C, U+006C, U+006F 
Hello: U+0048, U+0065, U+006C, U+006C, U+006F 

and therefore "Hello" < "hello".

The "normalization" or "decomposing" is relevant e.g. for characters with diacritical marks. As an example,

a = U+0061
ä = U+00E4
b = U+0062

have the decomposed form

a: U+0061
ä: U+0061, U+0308  // LATIN SMALL LETTER A + COMBINING DIAERESIS
b: U+0062

and therefore "a" < "ä" < "b".

For more details and examples, see What does it mean that string and character comparisons in Swift are not locale-sensitive?

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

The two strings are compared, character by character, using each character's Unicode value. Since h has a higher code (U+0068) than H (U+0048), str1 is "greater" than str2.

Based on Martin's comment below the question, it's slightly more complex than I stated. Please see What does it mean that string and character comparisons in Swift are not locale-sensitive? for more detail.

Community
  • 1
  • 1
rmaddy
  • 314,917
  • 42
  • 532
  • 579
0

I think it is based on the Lexicographical Order.https://en.wikipedia.org/wiki/Lexicographical_order

Harsh
  • 2,852
  • 1
  • 13
  • 27
0

In Swift 4.2 - //Unicode Value gives you an idea why "hello" is greater than "Hello" as the length of both Strings are the same.

var str1 = "hello"
var str2 = "Hello"

if (str1 < str2){
    print("hello is less than Hello")
}
else {
    print("hello is more than Hello")
}

print(str1.unicodeScalars[str1.unicodeScalars.startIndex].value)
print(str2.unicodeScalars[str2.unicodeScalars.startIndex].value)