【问题标题】:sorting array of objects swift 4快速排序对象数组4
【发布时间】:2018-01-30 19:01:19
【问题描述】:

我有一个对象数组,每个对象都包含一个折扣率,我需要按它们的比率对它们进行越来越多的排序,

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

    }

我尝试将速率转换为整数,因为它是从后端作为字符串接收的,但我收到错误: value of type Any has no member discountRate. 知道怎么做吗?如果有办法不用强制转换就更好了

【问题讨论】:

  • 某处有错字吗?错误消息有一个小写的discountrate,你的代码有discountRate。
  • 已编辑请检查
  • 什么是copyOfShops?它应该是[ShopDetails]——顺便避免了错误——但我猜它是NSArray
  • 它是包含我要排序的对象的数组,它是一个商店数组
  • 为什么discountRate 是一个(可选的)字符串?让它成为一个 Double 并省去麻烦!

标签: arrays swift sorting


【解决方案1】:

首先,您需要验证您开始使用的数组是[ShopDetails] 类型。该错误表明这可能是一个 Objective-C NSArray,它在 Swift 中无法正常工作。如果你对此不清楚,我建议你谷歌这个话题:没有理由在 Swift 中使用NSArray。

下面,我假设数组是正确的类型 ([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&lt;String,Any&gt;) 时进行上述检查。如果给你字典的服务器是你控制的,让它切换到传回 In​​ts 而不是 Strings,如果你不需要,就停止处理可选项。

【讨论】:

    猜你喜欢
    • 2021-06-15
    • 2012-01-07
    • 1970-01-01
    • 1970-01-01
    • 2011-06-02
    • 2015-05-01
    • 2015-11-19
    • 1970-01-01
    相关资源
    最近更新 更多