Sorting an array of tuples in swift 3

Hi, I have the following

class MyClass {
  var myString: String?
}

var myClassList = [String: MyClass]()

I would like to sort this array alphabetically of the variable myString in Swift 3 by any pointer?

0
source share
2 answers

Cool problem! Although I would like to indicate first what [String: MyClass]is a Dictionary, not a Tupule.

However, Swift does support Tupules. The syntax for your tupule will look like this:

var tupule: (String, MyClass) = (foo, bar)

Then you will need to create an array of them:

var tupules:[(String, MyClass)] = [(foo, bar), (up, dog)]

Then you can sort this array:

tupules.sort({ $0[1].myString > $1[1].myString })

although you probably should define a more robust sorting mechanism.

This is the contents of the close sort:

$0 - , , $1 - . $0 [1] $1 [1] 1, , tupule, MyClass

, .

+1

, , . sorted(by:), /. :

var m: [String: Int] = ["a": 1]
let n = m.sorted(by: { (first: (key: String, value: Int), second: (key: String, value: Int)) -> Bool in
  return first.value > second.value
})

, , :

let n = m.sorted(by: {
  return $0.value > $1.value
})

,

m.forEach { (element: (key: String, value: Int)) in
  print($0.value)
}

Swift, .

0

Source: https://habr.com/ru/post/1671318/


All Articles