谁能帮我理解为什么。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
当我调用时。在我的字典上像这样排序:
let sortDict = wordDict.sort { $0.0 < $1.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字典,当您需要根据它们的标识符查找值时,就像现实世界里的字典一样特定单词的定义
这里说明,https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/CollectionTypes.html#//apple_ref/doc/uid/TP40014097-CH8-ID113
所以,你不能有排序字典。即使您对键进行排序并逐一赋值,也不能保证键和值仍然按照分配的顺序排序。
唯一的方法是对键进行排序,然后为每个排序的键逐个提取值。
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]
}
这里排序方法返回[Self.Generator.Element]。在您的情况下,您有序列类型字典即[String: [String]],因此元素类型是(Key, Value) => (String, [String]),排序时应返回[(Key, Value)] => [(String, [String])]。这就是你得到的。
或者你可以创建一些结构或类类型,其中键作为标识符,然后值将是一些其他属性。然后你可以把它添加到数组中。
下面是一个如何用上面的数据创建一个分段表视图的例子,
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方法进行排序,并对每个数据源方法进行一些计算。你可以自己修改:)