0

Hello I want to sort an array over two properties. How can I do this in swift?

This is how my code looks right now.

import Foundation

class AutosuggestModel {

    var type = ""
    var count = 0

    init(type: String, count: Int) {
        self.type = type
        self.count = count
    }

}

let array = [AutosuggestModel(type:"brand",count:10),AutosuggestModel(type:"brand",count:7),AutosuggestModel(type:"model",count:300),AutosuggestModel(type:"model",count:500),AutosuggestModel(type:"brand",count:50)]

The sorting should also include the type of the object. If the type is "brand" than it should be ordered higher than type model and also in relation to the count property. So the right order for my example should be this:

[AutosuggestModel(type:"brand",count:50),AutosuggestModel(type:"brand",count:10),AutosuggestModel(type:"brand",count:7),AutosuggestModel(type:"model",count:500),AutosuggestModel(type:"model",count:300)]

My sorting looks now like this:

let ordered = array.sorted(by: {$0.count > $1.count})
Kingalione
  • 4,237
  • 6
  • 49
  • 84
  • 1
    Instead of `{$0.count > $1.count}`, compare first the type, if it's the same compare the count, else, return according to if it's brand or not. – Larme Jan 11 '17 at 09:32
  • How can I add if conditions to the sorting function and return values from there? I very new into the sorting functionality in swift – Kingalione Jan 11 '17 at 09:36
  • thanks for your hint I solved it. – Kingalione Jan 11 '17 at 09:48

0 Answers0