0

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

所以它对它们进行了组织,但由于某种原因,我有了一种新的类型。

我的问题:

为什么排序给了我一个新的类型?另外,对我的字典进行排序的正确方法是什么?

4

1 回答 1

1

请注意,字典是键和值的无序集合。

从文档中可以看出,

字典在没有定义排序的集合中存储相同类型的键和相同类型的值之间的关联。每个值都与一个唯一键相关联,该键充当字典中该值的标识符。与数组中的项目不同,字典中的项目没有指定的顺序。当您需要根据标识符查找值时,您可以使用字典,这与使用现实世界的字典查找特定单词的定义的方式非常相似。

此处说明,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]
}

这里 sort 方法返回[Self.Generator.Element]。在您的情况下,您有序列类型的Dict[String: [String]],因此元素类型是(Key, Value) => (String, [String])排序时应返回[(Key, Value)] = > [(字符串,[字符串])]。这就是你得到的。

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

这是一个示例,说明如何使用上面的数据创建分段的 tableview,

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

于 2015-09-03T19:44:31.933 回答