iOS Swift:数组按值排序时,string转float的地方
iOS Swift: when sorting an array by value, where to convert string to float
在 iOS Swift 中,我按照以下代码对数组进行降序排序。代码工作正常,但是,'Price' 不是双精度而是字符串(因此目前代码在多位数时会出错)。
如何在此单行排序函数中将字符串 'Price' 转换为双精度数?
OfferList.sort { [=12=].Price > .Price }
我知道在将排序写成多行循环时有一些方法可以做到这一点,但是有没有办法直接在上面的行中做到这一点?
Double
有一个可以接受 StringProtocol
的初始值设定项,当然它是 returns 和 Optional
,因为字符串实际上可能是也可能不是数字。为了将您的字符串排序为双打,您需要一个回退选项以防它失败,否则如果您可以保证它们始终是双打,您将需要强制解包这些 init
。选项如下所示:
//Fallback using a nil-coalescing operator
OfferList.sort { (Double([=10=].Price) ?? 0) > (Double(.Price) ?? 0) }
//Force unwrapping
OfferList.sort { Double([=10=].Price)! > Double(.Price)! }
作为一个无关紧要的小问题,以驼峰命名法命名对象的变量和属性被认为是最佳实践,例如 offerList
和 [=16=].price
。当然,这不是必需的,但这是其他 Swift 开发人员所期望的。
使用NSArray 的Sorted 方法从Dictionary Value 转换和排序。使用以下代码进行排序。
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
在 iOS Swift 中,我按照以下代码对数组进行降序排序。代码工作正常,但是,'Price' 不是双精度而是字符串(因此目前代码在多位数时会出错)。
如何在此单行排序函数中将字符串 'Price' 转换为双精度数?
OfferList.sort { [=12=].Price > .Price }
我知道在将排序写成多行循环时有一些方法可以做到这一点,但是有没有办法直接在上面的行中做到这一点?
Double
有一个可以接受 StringProtocol
的初始值设定项,当然它是 returns 和 Optional
,因为字符串实际上可能是也可能不是数字。为了将您的字符串排序为双打,您需要一个回退选项以防它失败,否则如果您可以保证它们始终是双打,您将需要强制解包这些 init
。选项如下所示:
//Fallback using a nil-coalescing operator
OfferList.sort { (Double([=10=].Price) ?? 0) > (Double(.Price) ?? 0) }
//Force unwrapping
OfferList.sort { Double([=10=].Price)! > Double(.Price)! }
作为一个无关紧要的小问题,以驼峰命名法命名对象的变量和属性被认为是最佳实践,例如 offerList
和 [=16=].price
。当然,这不是必需的,但这是其他 Swift 开发人员所期望的。
使用NSArray 的Sorted 方法从Dictionary Value 转换和排序。使用以下代码进行排序。
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