0

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.

3
  • 5
    Your array is actually a dictionary. A dictionary is unordered by definition. Commented Oct 30, 2017 at 5:26
  • Check this : stackoverflow.com/questions/35431754/… . if it helps in your scenario. Commented Oct 30, 2017 at 5:36
  • 1
    let sortedTuples = filteredObjects.sorted{ $0.value.distance < $1.value.distance } Commented Oct 30, 2017 at 5:37

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Btw by using the parentheses you need to add the by: keyword
And you can’t use sort. Dictionary is an unordered collection
I have already up voted your comment. I tried to explain why @Vad is getting that error.
again by using the parentheses you need to add the by: keyword .sorted(by: { ... }) or remove the parentheses .sorted { ... }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.