我有一个对象数组,每个对象都包含一个折扣率,我需要按折扣率对它们进行递增排序,
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?
.
- 您需要检查字符串是否确实存在
- 你需要检查它是否真的可以表示为
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>)
时执行上述检查.如果为您提供字典的服务器是您可以控制的,请将其切换为传回 Ints 而不是 Strings,并在不需要时停止处理可选值。
关于arrays - 排序对象数组swift 4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48528698/