Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: sort array with alternative comparison

I'd like to sort my swift struct array using another comparison method (like localizedCompare, caseInsensitiveCompare or localizedCaseInsensitiveCompare). The swift standard string array sort function orders all uppercase letters before lowercase letters. Here's my code:

import Foundation

struct DataStruct {

    struct Item {
        let title: String
        let number: Int
    }

        static var items = [
        Item(title: "apple", number: 30),
        Item(title: "Berry", number: 9),
        Item(title: "apple", number: 18)]
}

class DataFunctions {
    func sortItemsArrayTitle() {
        DataStruct.items.sort { $0.title < $1.title }
    }
}

Once called, the above code results in [Berry, apple, apple]. Unacceptable. Any suggestions?

like image 293
Shane Avatar asked May 23 '15 23:05

Shane


People also ask

How do you sort an array of objects alphabetically in Swift?

You can use array. sorted() as an alternative for array. sorted(by: <) .


1 Answers

You can easily solve it by comparing the title lowercaseString as follow:

DataStruct.items.sort { $0.title.lowercaseString < $1.title.lowercaseString }

using localizedCompare it should look like this:

DataStruct.items.sort { $0.title.localizedCompare($1.title) == .OrderedAscending } 
like image 187
Leo Dabus Avatar answered Sep 22 '22 12:09

Leo Dabus