在字典上调用 .sort 会创建一个新类型?
Calling .sort on dictionary creates a new type?
有人可以帮我理解为什么 .sort 给我一个新类型吗?
我有这样的字典:
var wordDict : [String : [String]]
其中包含未组织的键:
["H": ["Hal", "Hamilton", "Hank", "Hans", "Harmon", "Harold", "Harris", "Harry", "Hartmann", "Harv", "Harvey", "Hazel", "Heather", "Hector", "Heidi", "Hein", "Heinrich", "Heinz", "Helen", "Helge", "Henry", "Herb", "Herbert", "Herman", "Herve", "Hienz", "Hilda", "Hillary", "Hillel", "Himawan", "Hirofumi", "Hirotoshi", "Hiroyuki", "Hitoshi", "Hohn", "Holly", "Hon", "Honzo", "Horst", "Hotta", "Howard", "Hsi", "Hsuan", "Huashi", "Hubert", "Huey", "Hugh", "Hughes", "Hui", "Hume", "Hunter", "Hurf", "Hwa", "Hy"], "V": ["Vadim", "Val", "Valentin", "Valeria", "Valerie", "Van", "Vance", "Varda", "Vassos", "Vaughn", "Venkata", "Vern", "Vernon", "Vic", "Vice", "Vick", "Vicki", "Vickie", "Vicky", "Victor", "Victoria", "Vidhyanath", "Vijay", "Vilhelm", "Vince", "Vincent", "Vincenzo", "Vinod", "Vishal", "Vistlik", "Vivek", "Vladimir", "Vladislav"], "D": ["Dale", "Dalton", "Damon", "Damone", "Dan", "Dana", "Dani", "Daniel", "Daniele", "Danielle", "Dannie", "Danny", "Darci", "Daren", "Darin", "Darrell", "Darren", "Darryl", "Daryl", "Dave", "David", "Dawn", "Dawson", "Dean", "Deb", "Debbie", "Debi", "Deborah", "Deirdre", "Del", "Delbert", "Denis", "Dennis", "Derek", "Devon", "Dewey", "Diana", "Diane", "Dick", "Dieter", "Dimetry", "Dimitry", "Dion", "Dirk", "Dominic", "Dominick", "Don", "Donal", "Donald", "Donn", "Donna", "Donne", "Donnie", "Donovan", "Dori", "Dorian", "Dorothy", "Dory", "Doug", "Douglas", "Doyle", "Drew", "Duane", "Duke", "Duncan", "Dustin", "Dwayne", "Dwight", "Dylan"]... and so on
当我像这样在我的字典上调用 .sort 时:
let sortDict = wordDict.sort { [=12=].0 < .0 }
sortDict 现在有一个意外的类型 [(String:[String])]
,看起来像这样:
[("A", ["Aaron", "Adam", "Adlai", "Adrian", "Agatha", "Ahmed", "Ahmet", "Aimee", "Al", "Alain", "Alan", "Alastair", "Albert", "Alberto", "Alejandro", "Alex", "Alexander", "Alexis", "Alf", "Alfred", "Alison", "Allan", "Allen", "Alvin", "Amanda", "Amarth", "Amedeo", "Ami", "Amigo", "Amir", "Amos", "Amy", "Anatole", "Anatoly", "Anderson", "Andre", "Andrea", "Andreas", "Andrew", "Andries", "Andy", "Angela", "Angus", "Anita", "Ann", "Anna", "Annard", "Anne", "Annie", "Anthony", "Anton", "Antonella", "Antonio", "Antony", "Archie", "Ariel", "Arlene", "Arne", "Arnold", "Art", "Arthur", "Audrey", "Avery", "Axel"])... and so on
所以它组织了他们,但出于某种原因我有一个新类型。
我的问题:
为什么 sort 给我一个新类型?另外,我的字典排序的正确方法是什么?
请注意,字典是键和值的无序集合。
根据文档,它说明如下,
A dictionary stores associations between keys of the same type and
values of the same type in an collection with no defined ordering.
Each value is associated with a unique key, which acts as an
identifier for that value within the dictionary. Unlike items in an
array, items in a dictionary do not have a specified order. You use a
dictionary when you need to look up values based on their identifier,
in much the same way that a real-world dictionary is used to look up
the definition for a particular word.
因此,您不能对字典进行排序。即使您对键进行排序并一一分配,也不能保证键和值保持按分配顺序排序。
您可以做的唯一方法是对键进行排序,然后为每个排序后的键一个一个地提取值。
let myDict = ["H": ["Hal", "Hamilton", "Hank", "Hans", "Harmon", "Harold", "Harris", "Harry", "Hartmann", "Harv", "Harvey", "Hazel", "Heather", "Hector", "Heidi", "Hein", "Heinrich", "Heinz", "Helen", "Helge", "Henry", "Herb", "Herbert", "Herman", "Herve", "Hienz", "Hilda", "Hillary", "Hillel", "Himawan", "Hirofumi", "Hirotoshi", "Hiroyuki", "Hitoshi", "Hohn", "Holly", "Hon", "Honzo", "Horst", "Hotta", "Howard", "Hsi", "Hsuan", "Huashi", "Hubert", "Huey", "Hugh", "Hughes", "Hui", "Hume", "Hunter", "Hurf", "Hwa", "Hy"], "V": ["Vadim", "Val", "Valentin", "Valeria", "Valerie", "Van", "Vance", "Varda", "Vassos", "Vaughn", "Venkata", "Vern", "Vernon", "Vic", "Vice", "Vick", "Vicki", "Vickie", "Vicky", "Victor", "Victoria", "Vidhyanath", "Vijay", "Vilhelm", "Vince", "Vincent", "Vincenzo", "Vinod", "Vishal", "Vistlik", "Vivek", "Vladimir", "Vladislav"], "D": ["Dale", "Dalton", "Damon", "Damone", "Dan", "Dana", "Dani", "Daniel", "Daniele", "Danielle", "Dannie", "Danny", "Darci", "Daren", "Darin", "Darrell", "Darren", "Darryl", "Daryl", "Dave", "David", "Dawn", "Dawson", "Dean", "Deb", "Debbie", "Debi", "Deborah", "Deirdre", "Del", "Delbert", "Denis", "Dennis", "Derek", "Devon", "Dewey", "Diana", "Diane", "Dick", "Dieter", "Dimetry", "Dimitry", "Dion", "Dirk", "Dominic", "Dominick", "Don", "Donal", "Donald", "Donn", "Donna", "Donne", "Donnie", "Donovan", "Dori", "Dorian", "Dorothy", "Dory", "Doug", "Douglas", "Doyle", "Drew", "Duane", "Duke", "Duncan", "Dustin", "Dwayne", "Dwight", "Dylan"]]
let sortedKeys = myDict.keys.sort()
sortedKeys.forEach { aKey in
print(myDict[aKey])
}
如果您查看 swift 头文件,您将看到协议 SequenceType 的以下声明。
extension SequenceType where Self.Generator.Element : Comparable {
/// Return an `Array` containing the sorted elements of `source`.
///
/// The sorting algorithm is not stable (can change the relative order of
/// elements that compare equal).
///
/// - Requires: The less-than operator (`func <`) defined in
/// the `Comparable` conformance is a
/// [strict weak ordering](http://en.wikipedia.org/wiki/Strict_weak_order#Strict_weak_orderings)
/// over the elements in `self`.
@warn_unused_result
public func sort() -> [Self.Generator.Element]
}
这里排序方法returns [Self.Generator.Element]。在您的情况下,您的序列类型为 Dict 即 [String: [String]] 等 Element 类型是 (Key, Value) => (String, [String]) 排序时应该 return [(Key, Value)] => [(字符串,[字符串])]。这就是你得到的。
或者您可以创建一些结构或 class 类型,它具有键作为标识符,然后值将是一些其他属性。然后你可以将 then 添加到数组中。
这是一个示例,说明如何使用上述数据创建分段表视图,
class ViewController: UIViewController {
internal class MyView: UIView, UITableViewDataSource {
let myDict = ["H": ["Hal", "Hamilton", "Hank", "Hans", "Harmon", "Harold", "Harris", "Harry", "Hartmann", "Harv", "Harvey", "Hazel", "Heather", "Hector", "Heidi", "Hein", "Heinrich", "Heinz", "Helen", "Helge", "Henry", "Herb", "Herbert", "Herman", "Herve", "Hienz", "Hilda", "Hillary", "Hillel", "Himawan", "Hirofumi", "Hirotoshi", "Hiroyuki", "Hitoshi", "Hohn", "Holly", "Hon", "Honzo", "Horst", "Hotta", "Howard", "Hsi", "Hsuan", "Huashi", "Hubert", "Huey", "Hugh", "Hughes", "Hui", "Hume", "Hunter", "Hurf", "Hwa", "Hy"], "V": ["Vadim", "Val", "Valentin", "Valeria", "Valerie", "Van", "Vance", "Varda", "Vassos", "Vaughn", "Venkata", "Vern", "Vernon", "Vic", "Vice", "Vick", "Vicki", "Vickie", "Vicky", "Victor", "Victoria", "Vidhyanath", "Vijay", "Vilhelm", "Vince", "Vincent", "Vincenzo", "Vinod", "Vishal", "Vistlik", "Vivek", "Vladimir", "Vladislav"], "D": ["Dale", "Dalton", "Damon", "Damone", "Dan", "Dana", "Dani", "Daniel", "Daniele", "Danielle", "Dannie", "Danny", "Darci", "Daren", "Darin", "Darrell", "Darren", "Darryl", "Daryl", "Dave", "David", "Dawn", "Dawson", "Dean", "Deb", "Debbie", "Debi", "Deborah", "Deirdre", "Del", "Delbert", "Denis", "Dennis", "Derek", "Devon", "Dewey", "Diana", "Diane", "Dick", "Dieter", "Dimetry", "Dimitry", "Dion", "Dirk", "Dominic", "Dominick", "Don", "Donal", "Donald", "Donn", "Donna", "Donne", "Donnie", "Donovan", "Dori", "Dorian", "Dorothy", "Dory", "Doug", "Douglas", "Doyle", "Drew", "Duane", "Duke", "Duncan", "Dustin", "Dwayne", "Dwight", "Dylan"]]
override init(frame: CGRect) {
super.init(frame: frame)
let tableView = UITableView(frame: frame)
tableView.autoresizingMask = [UIViewAutoresizing.FlexibleHeight, UIViewAutoresizing.FlexibleWidth]
tableView.dataSource = self
addSubview(tableView)
}
required init?(coder aDecoder: NSCoder) {
fatalError("Not supported")
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return myDict.keys.count
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let keys = myDict.keys.sort()
let keyForSection = keys[section]
let rowCount = myDict[keyForSection]!.count
return rowCount
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cellIdentifier = "CellIdentifier"
var cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier)
if cell == nil {
cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: cellIdentifier)
}
let keys = myDict.keys.sort()
let keyForSection = keys[indexPath.section]
let rowItem = myDict[keyForSection]!.sort()[indexPath.row]
cell?.textLabel?.text = rowItem
return cell!
}
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
let keys = myDict.keys.sort()
let keyForSection = keys[section]
return keyForSection
}
func sectionIndexTitlesForTableView(tableView: UITableView) -> [String]? {
let keys = myDict.keys.sort()
return keys
}
}
override func viewDidLoad() {
super.viewDidLoad()
edgesForExtendedLayout = UIRectEdge.None
let myView = MyView(frame: view.bounds)
myView.autoresizingMask = [.FlexibleHeight, .FlexibleWidth]
view.addSubview(myView)
}
}
上面的例子只是展示了你是如何做到的。它的性能不好,因为它在每个 tableview cellForRowAtIndexPath 方法上进行排序,并对每个数据源方法进行一些计算。你可以自己改进:)
有人可以帮我理解为什么 .sort 给我一个新类型吗?
我有这样的字典:
var wordDict : [String : [String]]
其中包含未组织的键:
["H": ["Hal", "Hamilton", "Hank", "Hans", "Harmon", "Harold", "Harris", "Harry", "Hartmann", "Harv", "Harvey", "Hazel", "Heather", "Hector", "Heidi", "Hein", "Heinrich", "Heinz", "Helen", "Helge", "Henry", "Herb", "Herbert", "Herman", "Herve", "Hienz", "Hilda", "Hillary", "Hillel", "Himawan", "Hirofumi", "Hirotoshi", "Hiroyuki", "Hitoshi", "Hohn", "Holly", "Hon", "Honzo", "Horst", "Hotta", "Howard", "Hsi", "Hsuan", "Huashi", "Hubert", "Huey", "Hugh", "Hughes", "Hui", "Hume", "Hunter", "Hurf", "Hwa", "Hy"], "V": ["Vadim", "Val", "Valentin", "Valeria", "Valerie", "Van", "Vance", "Varda", "Vassos", "Vaughn", "Venkata", "Vern", "Vernon", "Vic", "Vice", "Vick", "Vicki", "Vickie", "Vicky", "Victor", "Victoria", "Vidhyanath", "Vijay", "Vilhelm", "Vince", "Vincent", "Vincenzo", "Vinod", "Vishal", "Vistlik", "Vivek", "Vladimir", "Vladislav"], "D": ["Dale", "Dalton", "Damon", "Damone", "Dan", "Dana", "Dani", "Daniel", "Daniele", "Danielle", "Dannie", "Danny", "Darci", "Daren", "Darin", "Darrell", "Darren", "Darryl", "Daryl", "Dave", "David", "Dawn", "Dawson", "Dean", "Deb", "Debbie", "Debi", "Deborah", "Deirdre", "Del", "Delbert", "Denis", "Dennis", "Derek", "Devon", "Dewey", "Diana", "Diane", "Dick", "Dieter", "Dimetry", "Dimitry", "Dion", "Dirk", "Dominic", "Dominick", "Don", "Donal", "Donald", "Donn", "Donna", "Donne", "Donnie", "Donovan", "Dori", "Dorian", "Dorothy", "Dory", "Doug", "Douglas", "Doyle", "Drew", "Duane", "Duke", "Duncan", "Dustin", "Dwayne", "Dwight", "Dylan"]... and so on
当我像这样在我的字典上调用 .sort 时:
let sortDict = wordDict.sort { [=12=].0 < .0 }
sortDict 现在有一个意外的类型 [(String:[String])]
,看起来像这样:
[("A", ["Aaron", "Adam", "Adlai", "Adrian", "Agatha", "Ahmed", "Ahmet", "Aimee", "Al", "Alain", "Alan", "Alastair", "Albert", "Alberto", "Alejandro", "Alex", "Alexander", "Alexis", "Alf", "Alfred", "Alison", "Allan", "Allen", "Alvin", "Amanda", "Amarth", "Amedeo", "Ami", "Amigo", "Amir", "Amos", "Amy", "Anatole", "Anatoly", "Anderson", "Andre", "Andrea", "Andreas", "Andrew", "Andries", "Andy", "Angela", "Angus", "Anita", "Ann", "Anna", "Annard", "Anne", "Annie", "Anthony", "Anton", "Antonella", "Antonio", "Antony", "Archie", "Ariel", "Arlene", "Arne", "Arnold", "Art", "Arthur", "Audrey", "Avery", "Axel"])... and so on
所以它组织了他们,但出于某种原因我有一个新类型。
我的问题:
为什么 sort 给我一个新类型?另外,我的字典排序的正确方法是什么?
请注意,字典是键和值的无序集合。
根据文档,它说明如下,
A dictionary stores associations between keys of the same type and values of the same type in an collection with no defined ordering. Each value is associated with a unique key, which acts as an identifier for that value within the dictionary. Unlike items in an array, items in a dictionary do not have a specified order. You use a dictionary when you need to look up values based on their identifier, in much the same way that a real-world dictionary is used to look up the definition for a particular word.
因此,您不能对字典进行排序。即使您对键进行排序并一一分配,也不能保证键和值保持按分配顺序排序。
您可以做的唯一方法是对键进行排序,然后为每个排序后的键一个一个地提取值。
let myDict = ["H": ["Hal", "Hamilton", "Hank", "Hans", "Harmon", "Harold", "Harris", "Harry", "Hartmann", "Harv", "Harvey", "Hazel", "Heather", "Hector", "Heidi", "Hein", "Heinrich", "Heinz", "Helen", "Helge", "Henry", "Herb", "Herbert", "Herman", "Herve", "Hienz", "Hilda", "Hillary", "Hillel", "Himawan", "Hirofumi", "Hirotoshi", "Hiroyuki", "Hitoshi", "Hohn", "Holly", "Hon", "Honzo", "Horst", "Hotta", "Howard", "Hsi", "Hsuan", "Huashi", "Hubert", "Huey", "Hugh", "Hughes", "Hui", "Hume", "Hunter", "Hurf", "Hwa", "Hy"], "V": ["Vadim", "Val", "Valentin", "Valeria", "Valerie", "Van", "Vance", "Varda", "Vassos", "Vaughn", "Venkata", "Vern", "Vernon", "Vic", "Vice", "Vick", "Vicki", "Vickie", "Vicky", "Victor", "Victoria", "Vidhyanath", "Vijay", "Vilhelm", "Vince", "Vincent", "Vincenzo", "Vinod", "Vishal", "Vistlik", "Vivek", "Vladimir", "Vladislav"], "D": ["Dale", "Dalton", "Damon", "Damone", "Dan", "Dana", "Dani", "Daniel", "Daniele", "Danielle", "Dannie", "Danny", "Darci", "Daren", "Darin", "Darrell", "Darren", "Darryl", "Daryl", "Dave", "David", "Dawn", "Dawson", "Dean", "Deb", "Debbie", "Debi", "Deborah", "Deirdre", "Del", "Delbert", "Denis", "Dennis", "Derek", "Devon", "Dewey", "Diana", "Diane", "Dick", "Dieter", "Dimetry", "Dimitry", "Dion", "Dirk", "Dominic", "Dominick", "Don", "Donal", "Donald", "Donn", "Donna", "Donne", "Donnie", "Donovan", "Dori", "Dorian", "Dorothy", "Dory", "Doug", "Douglas", "Doyle", "Drew", "Duane", "Duke", "Duncan", "Dustin", "Dwayne", "Dwight", "Dylan"]]
let sortedKeys = myDict.keys.sort()
sortedKeys.forEach { aKey in
print(myDict[aKey])
}
如果您查看 swift 头文件,您将看到协议 SequenceType 的以下声明。
extension SequenceType where Self.Generator.Element : Comparable {
/// Return an `Array` containing the sorted elements of `source`.
///
/// The sorting algorithm is not stable (can change the relative order of
/// elements that compare equal).
///
/// - Requires: The less-than operator (`func <`) defined in
/// the `Comparable` conformance is a
/// [strict weak ordering](http://en.wikipedia.org/wiki/Strict_weak_order#Strict_weak_orderings)
/// over the elements in `self`.
@warn_unused_result
public func sort() -> [Self.Generator.Element]
}
这里排序方法returns [Self.Generator.Element]。在您的情况下,您的序列类型为 Dict 即 [String: [String]] 等 Element 类型是 (Key, Value) => (String, [String]) 排序时应该 return [(Key, Value)] => [(字符串,[字符串])]。这就是你得到的。
或者您可以创建一些结构或 class 类型,它具有键作为标识符,然后值将是一些其他属性。然后你可以将 then 添加到数组中。
这是一个示例,说明如何使用上述数据创建分段表视图,
class ViewController: UIViewController {
internal class MyView: UIView, UITableViewDataSource {
let myDict = ["H": ["Hal", "Hamilton", "Hank", "Hans", "Harmon", "Harold", "Harris", "Harry", "Hartmann", "Harv", "Harvey", "Hazel", "Heather", "Hector", "Heidi", "Hein", "Heinrich", "Heinz", "Helen", "Helge", "Henry", "Herb", "Herbert", "Herman", "Herve", "Hienz", "Hilda", "Hillary", "Hillel", "Himawan", "Hirofumi", "Hirotoshi", "Hiroyuki", "Hitoshi", "Hohn", "Holly", "Hon", "Honzo", "Horst", "Hotta", "Howard", "Hsi", "Hsuan", "Huashi", "Hubert", "Huey", "Hugh", "Hughes", "Hui", "Hume", "Hunter", "Hurf", "Hwa", "Hy"], "V": ["Vadim", "Val", "Valentin", "Valeria", "Valerie", "Van", "Vance", "Varda", "Vassos", "Vaughn", "Venkata", "Vern", "Vernon", "Vic", "Vice", "Vick", "Vicki", "Vickie", "Vicky", "Victor", "Victoria", "Vidhyanath", "Vijay", "Vilhelm", "Vince", "Vincent", "Vincenzo", "Vinod", "Vishal", "Vistlik", "Vivek", "Vladimir", "Vladislav"], "D": ["Dale", "Dalton", "Damon", "Damone", "Dan", "Dana", "Dani", "Daniel", "Daniele", "Danielle", "Dannie", "Danny", "Darci", "Daren", "Darin", "Darrell", "Darren", "Darryl", "Daryl", "Dave", "David", "Dawn", "Dawson", "Dean", "Deb", "Debbie", "Debi", "Deborah", "Deirdre", "Del", "Delbert", "Denis", "Dennis", "Derek", "Devon", "Dewey", "Diana", "Diane", "Dick", "Dieter", "Dimetry", "Dimitry", "Dion", "Dirk", "Dominic", "Dominick", "Don", "Donal", "Donald", "Donn", "Donna", "Donne", "Donnie", "Donovan", "Dori", "Dorian", "Dorothy", "Dory", "Doug", "Douglas", "Doyle", "Drew", "Duane", "Duke", "Duncan", "Dustin", "Dwayne", "Dwight", "Dylan"]]
override init(frame: CGRect) {
super.init(frame: frame)
let tableView = UITableView(frame: frame)
tableView.autoresizingMask = [UIViewAutoresizing.FlexibleHeight, UIViewAutoresizing.FlexibleWidth]
tableView.dataSource = self
addSubview(tableView)
}
required init?(coder aDecoder: NSCoder) {
fatalError("Not supported")
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return myDict.keys.count
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let keys = myDict.keys.sort()
let keyForSection = keys[section]
let rowCount = myDict[keyForSection]!.count
return rowCount
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cellIdentifier = "CellIdentifier"
var cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier)
if cell == nil {
cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: cellIdentifier)
}
let keys = myDict.keys.sort()
let keyForSection = keys[indexPath.section]
let rowItem = myDict[keyForSection]!.sort()[indexPath.row]
cell?.textLabel?.text = rowItem
return cell!
}
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
let keys = myDict.keys.sort()
let keyForSection = keys[section]
return keyForSection
}
func sectionIndexTitlesForTableView(tableView: UITableView) -> [String]? {
let keys = myDict.keys.sort()
return keys
}
}
override func viewDidLoad() {
super.viewDidLoad()
edgesForExtendedLayout = UIRectEdge.None
let myView = MyView(frame: view.bounds)
myView.autoresizingMask = [.FlexibleHeight, .FlexibleWidth]
view.addSubview(myView)
}
}
上面的例子只是展示了你是如何做到的。它的性能不好,因为它在每个 tableview cellForRowAtIndexPath 方法上进行排序,并对每个数据源方法进行一些计算。你可以自己改进:)