Swift: sort array with alternative comparison

家住魔仙堡 提交于 2019-12-06 21:45:47

问题


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?


回答1:


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 } 


来源:https://stackoverflow.com/questions/30418553/swift-sort-array-with-alternative-comparison

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!