In Swift 3 I define my array as:
var filteredObjects = [Int: CustomObject]()
then I populate array with data:
filteredObjects[filteredObjects.count] = CustomObject
Now I want to sort array by (1) property "title" of CustomObject
which is a String
and (2) a float property "distance" of CustomObject
.
When I try:
filteredObjects.sort({ 0ドル.distance < 1ドル.distance })
it produces error Value of tuple type (key:Int, value:CustomObject) has no member distance
I suspect I cannot use sort
method like this but I cannot find the solution.
1 Answer 1
In swift 3: While using sort in filteredObjects i.e dictionary 0ドル will give you a single object from filteredObjects which will be of tuple type "((key: Int, value: CustomObject), (key: Int, value: CustomObject))". 0ドル.distance will actually try to find distance property in the tuple which isn't available in the result tuple, so you are getting error Value of tuple type (key:Int, value:CustomObject) has no member distance
What you can do is
let resultDictionary = filteredObjects.sorted() {
0ドル.0.value.distance < 0ドル.1.value.distance
}
0ドル.0.value is of type CustomObject which have property distance according to which you want to sort the result.
Special thanks to @Leo Dabus.
-
Btw by using the parentheses you need to add the by: keywordLeo Dabus– Leo Dabus2017年10月30日 05:48:15 +00:00Commented Oct 30, 2017 at 5:48
-
And you can’t use sort. Dictionary is an unordered collectionLeo Dabus– Leo Dabus2017年10月30日 05:49:40 +00:00Commented Oct 30, 2017 at 5:49
-
I have already up voted your comment. I tried to explain why @Vad is getting that error.laxman khanal– laxman khanal2017年10月30日 05:51:43 +00:00Commented Oct 30, 2017 at 5:51
-
again by using the parentheses you need to add the
by:
keyword.sorted(by: { ... })
or remove the parentheses.sorted { ... }
Leo Dabus– Leo Dabus2017年10月30日 13:46:26 +00:00Commented Oct 30, 2017 at 13:46
let sortedTuples = filteredObjects.sorted{ 0ドル.value.distance < 1ドル.value.distance }