[英]iOS Swift: when sorting an array by value, where to convert string to float
在 iOS Swift 中,我按照下面的代码按降序对数组进行排序。 该代码工作正常,但是,'Price' 不是双精度值而是字符串(因此当前代码在是多位数字时会出错)。
如何在此单行排序函数中将字符串 'Price' 转换为双精度值?
OfferList.sort { $0.Price > $1.Price }
我知道在将排序编写为多行循环时有办法做到这一点,但是有没有办法直接在上面的行中做到这一点?
Double
有一个可以接受StringProtocol
的初始化程序,当然它返回一个Optional
因为字符串实际上可能是也可能不是数字。 为了将您的字符串排序为双打,您需要一个回退选项,以防它失败,否则,如果您可以保证它们始终是双打,则您需要强制解包这些init
。 选项如下所示:
//Fallback using a nil-coalescing operator
OfferList.sort { (Double($0.Price) ?? 0) > (Double($1.Price) ?? 0) }
//Force unwrapping
OfferList.sort { Double($0.Price)! > Double($1.Price)! }
作为一个小的,不相关的,以驼峰命名命名对象的变量和属性被认为是最佳实践,如offerList
和$0.price
。 当然,这不是必需的,但这是其他 Swift 开发人员所期望的。
使用 NSArray 的 Sorted 方法对字典值进行转换和排序。 使用下面的代码进行排序。
let sortedResults: NSArray = arry.sorted { (obj1, obj2) -> Bool in
if ((obj1 as! NSDictionary).allKeys as NSArray).contains("id") && ((obj2 as! NSDictionary).allKeys as NSArray).contains("id"){
return Float((obj1 as! NSDictionary)["id"] as! String)! < Float((obj2 as! NSDictionary)["id"] as! String)!
}
else{
return true
}
} as NSArray
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.