在 Swift 3 中,我将数组定义为:
var filteredObjects = [Int: CustomObject]()
然后我用数据填充数组:
filteredObjects[filteredObjects.count] = CustomObject
现在我想按 (1) CustomObject
的属性“title”(String
)和 (2) 的浮点属性“distance”对数组进行排序>自定义对象
。
当我尝试时:
filteredObjects.sort({ $0.distance < $1.distance })
它产生错误Value of tuple type (key:Int, value:CustomObject) has no member distance
我怀疑我不能像这样使用 sort
方法,但我找不到解决方案。
最佳答案
在 swift 3 中: 在 filteredObjects 中使用排序时,即字典 $0 将为您提供 filteredObjects 中的单个对象,该对象将是元组类型 "((key: Int, value: CustomObject), (key: Int, value: CustomObject))”。 $0.distance 实际上会尝试在结果元组中不可用的元组中查找距离属性,因此您会收到错误消息 Value of tuple type (key:Int, value:CustomObject) has no member distance强>
你能做的是
let resultDictionary = filteredObjects.sorted() {
$0.0.value.distance < $0.1.value.distance
}
$0.0.value 属于 CustomObject 类型,它具有您要根据其对结果进行排序的属性 distance。
特别感谢@Leo Dabus。
关于arrays - swift 3 : Sort Ordered List of Objects by Property,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47008519/