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.

asked Oct 30, 2017 at 5:19
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.

answered Oct 30, 2017 at 5:45
4
  • Btw by using the parentheses you need to add the by: keyword Commented Oct 30, 2017 at 5:48
  • And you can’t use sort. Dictionary is an unordered collection Commented Oct 30, 2017 at 5:49
  • I have already up voted your comment. I tried to explain why @Vad is getting that error. Commented 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 { ... } Commented Oct 30, 2017 at 13:46

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.