【发布时间】: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 并省去麻烦!