arrays - swift 3 : Sort Ordered List of Objects by Property

标签 arrays swift sorting swift3

在 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/

相关文章:

javascript - 旧对象去哪儿了?

android - 从 android 中的字符串数组引用可绘制对象

c - 在C中,如何找到数组中元素的偏移量

ios - 如何在 iOS UItest 中选择本地化的日期选择器项目

ios - 无法通过 Cocoapods 安装 RealmSwift

ios - NSNotificationCenter PasteboardChangedNotification 未触发

arrays - StreamBuilder arrayContains和RangeError(索引):无效值:有效值范围为空:0

c - 字符串的第一个非重复字符

algorithm - 对图书馆中几乎已排序的书籍进行排序的最佳算法是什么

java - Java的Collections.sort如何覆盖待排序的List