在Swift 3中对元组数组进行排序 [英] Sort an array of tuples in swift 3

查看:121
本文介绍了在Swift 3中对元组数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下

class MyClass {
  var myString: String?
}

var myClassList = [String: MyClass]()

我想通过Swift 3中的myString变量按字母顺序对数组进行排序吗?

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

推荐答案

如上所述,您拥有的是字典,而不是元组. 但是,词典确实具有sorted(by:)方法,可用于对键/值对元组数组进行排序.这是一个示例:

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)
}

所有这些都是由于Swift中的Collection和sequence协议层次结构,它们是一些非常不错的抽象.

All of this is due to the Collection and sequence protocol hierarchies in Swift, they're some pretty nice abstractions.

这篇关于在Swift 3中对元组数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆