arrays - 排序对象数组swift 4

标签 arrays swift sorting

我有一个对象数组,每个对象都包含一个折扣率,我需要按折扣率对它们进行递增排序,

struct ShopDetails {
    var shopId: Int?
    var discountRate: String?
    init(with json: Dictionary<String,Any>) {
        shopId = json["id"] as? Int
        discountRate = json["discount"] as? String

    }

我厌倦了使用这种方法对它们进行排序;

 func getShopsByDiscount() {
        let sortedImages = self.copyOfShops.sorted(by: { (shop1: ShopDetails, shop2: ShopDetails) -> Bool in
            return Int(shop1.discountRate) < Int(shop2.discountRate)
        })

    }

我试图将速率转换为整数,因为它是作为字符串从后端接收的,但我得到了一个错误: Any 类型的值没有成员折扣率。 知道怎么做吗?如果有一种不用强制转换的方法就更好了

最佳答案

首先,您需要验证开始使用的数组的类型是 [ShopDetails] .该错误表明这可能是一个 Objective-C NSArray ,这在 Swift 中效果不佳。如果你不清楚这一点,我建议你谷歌主题:没有理由使用 NSArray在 Swift 中。

下面,我假设数组是正确的类型 ( [ShopDetails] )。从这里开始,您需要做两件事,因为 discountRate类型为 String? .

  1. 您需要检查字符串是否确实存在
  2. 你需要检查它是否真的可以表示为 Int .

考虑到这些因素,您的排序函数可能如下所示:

let sortedImages = copyOfShops.sorted(by: {
    (shop1: ShopDetails, shop2: ShopDetails) -> Bool in
    if let shop1String = shop1.discountRate, let shop1Value = Int(shop1String),
        let shop2String = shop2.discountRate, let shop2Value = Int(shop2String) {
        return shop1Value < shop2Value
    }
    return true
})

也就是说,最好的处理方法是更改​​ discountRate 的类型来自 String?Int ,并在您 init(with json: Dictionary<String,Any>) 时执行上述检查.如果为您提供字典的服务器是您可以控制的,请将其切换为传回 In​​ts 而不是 Strings,并在不需要时停止处理可选值。

关于arrays - 排序对象数组swift 4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48528698/

相关文章:

php - 如何优化这个数组循环

javascript - 无法从数组中过滤对象

python - 如何提取 numpy 数组中值的索引?

swift - 如何在 Swift 中使用 Alamofire 网络进行解析时在请求中发送内容类型?

swift - 我可以在协议(protocol)中使用 @IBOutlets (Swift)

objective-c - 如何在 Swift 项目中使用 Objective-C CocoaPods

python - 一维列表索引 python : enhance MaskableList

java - 通用数组 - 无法编译

jquery - 如何制作2路 `up`和 `down` td文本 `sort`

r - 根据 r 中数字列表的顺序按升序对字符列表进行排序