斯威夫特:排序阵列方案比较 [英] Swift: sort array with alternative comparison

查看:214
本文介绍了斯威夫特:排序阵列方案比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想排序使用其他比较方法(如localizedCompare,caseInsensitiveCompare或localizedCaseInsensitiveCompare)我迅速的结构数组。雨燕标准字符串数组排序功能订单前小写字母全部大写字母。这里是我的code:

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 }
    }
}

一旦调用,上述code的结果[浆果,苹果,苹果。不能接受的。有什么建议?

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

推荐答案

您可以轻松地将标题lowercaseString比较如下解决这个问题:

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

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

使用localizedCompare它应该是这样的:

using localizedCompare it should look like this:

DataStruct.items.sort { $0.title.localizedCompare($1.title) == .OrderedAscending } 

这篇关于斯威夫特:排序阵列方案比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆