gpt4 book ai didi

arrays - 在字典上调用 .sort 会创建新类型吗?

转载 作者:行者123 更新时间:2023-11-30 10:12:08 25 4
gpt4 key购买 nike

有人可以帮我理解为什么 .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 { $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 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.

此处声明,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 头文件,您将看到协议(protocol) 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]。在您的情况下,您的序列类型为 Dict[String: [String]] ,因此 Element 类型为 (Key, Value) => (String, [String]) 排序后应返回 [(Key, Value)] => [(String, [String])]。这就是你得到的。

或者您可以创建一些结构或类类型,其中键作为标识符,然后值将是其他一些属性。然后您可以将 then 添加到数组中。

这是一个示例,说明如何使用上述数据创建分段表格 View ,

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 方法上进行排序,并对每个数据源方法进行一些计算。您可以自己完善它:)

关于arrays - 在字典上调用 .sort 会创建新类型吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32383916/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com