Hi I have the following
class MyClass {
var myString: String?
}
var myClassList = [String: MyClass]()
I would like to sort this array alphabetically by the myString variable in Swift 3 any pointers?
As mentioned above, you have a dictionary, not tuples.
However, Dictionaries do indeed have a sorted(by:)
method that you can use to sort an array of Key/Value pair tuples. Here's an example:
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
})
That's expanded to show the full signature of the closure, however easily shorthanded to:
let n = m.sorted(by: {
return $0.value > $1.value
})
Additionally, you can also perform other enumerations over Dictionaries
m.forEach { (element: (key: String, value: Int)) in
print($0.value)
}
All of this is due to the Collection and sequence protocol hierarchies in Swift, they're some pretty nice abstractions.
Cool problem! Though i'd like to point out first that
[String: MyClass]
is a Dictionary and not at Tupule.Swift does, however, support Tupules. The syntax for your tupule would look like so:
You would then need to make an Array of them:
Then you could sort that array:
though you should probably define a more robust sort mechanism.
These are the contents of the sort closure:
Hope this helps.