Yi Jiang
Yi Jiang

Reputation: 4028

How to sort a name (String) list in Swift?

There is a name list without any order. How to sort name list by alphabet order? What I mean is how to compare two strings to find out greater one? Is there any existing method or function to do this like Java does?

In Java, we can use

"abc".compareTo("abb");

to compare strings greater or smaller.

Upvotes: 2

Views: 155

Answers (1)

Nilesh Patel
Nilesh Patel

Reputation: 6394

Yes. You can use sort function of array like below,

let names = ["Chris", "Alex", "Ewa", "Barry", "Daniella"]

var reversed = names.sort({s1,s2 in s1 < s2})

//var reversed = names.sort {$0 < $1} // Shorter version of Closure.

print(reversed)

Upvotes: 2

Related Questions