[英]iOS Swift: when sorting an array by value, where to convert string to float
In iOS Swift, I am sorting an array in descending order as per the below code.在 iOS Swift 中,我按照下面的代码按降序对数组进行排序。 The code works fine, however, 'Price' is not a double but a string (so currently the code makes some mistakes when it is multi-digit numbers).
该代码工作正常,但是,'Price' 不是双精度值而是字符串(因此当前代码在是多位数字时会出错)。
How can I convert the string 'Price' into a double within this one-line sorting function?如何在此单行排序函数中将字符串 'Price' 转换为双精度值?
OfferList.sort { $0.Price > $1.Price }
I know there are ways of doing it when writing the sort as a multi-line loop, but is there a way of doing it directly in the line above?我知道在将排序编写为多行循环时有办法做到这一点,但是有没有办法直接在上面的行中做到这一点?
Double
has an initializer that can take a StringProtocol
, though of course it returns an Optional
since the string may or may not actually be numbers. Double
有一个可以接受StringProtocol
的初始化程序,当然它返回一个Optional
因为字符串实际上可能是也可能不是数字。 In order to sort your strings as doubles you'll need a fallback option in case it fails, or else you'll need to force unwrap these init
s if you can guarantee they'll always be doubles.为了将您的字符串排序为双打,您需要一个回退选项,以防它失败,否则,如果您可以保证它们始终是双打,则您需要强制解包这些
init
。 The options look like this:选项如下所示:
//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)! }
As a small, unrelated aside, it is considered best practice to name variables and attributes of objects in camel case, like offerList
and $0.price
.作为一个小的,不相关的,以驼峰命名命名对象的变量和属性被认为是最佳实践,如
offerList
和$0.price
。 Not a requirement, of course, but this is what other Swift developers would be expecting.当然,这不是必需的,但这是其他 Swift 开发人员所期望的。
Use Sorted method of NSArray to convert and Sort from Dictionary Value.使用 NSArray 的 Sorted 方法对字典值进行转换和排序。 Use the below code to sort.
使用下面的代码进行排序。
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.