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 に予期しない type が追加されました[(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 が新しい型を与えるのはなぜですか? また、私の辞書をソートする適切な方法は何ですか?

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

したがって、辞書をソートすることはできません。キーをソートして1つずつ割り当てても、キーと値が割り当てられた順序でソートされたままになるという保証はありません。

唯一の方法は、キーを並べ替えてから、並べ替えられたキーごとに値を 1 つずつ抽出することです。

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 ie [String: [String]]の Sequence タイプがあるため、Elementタイプは(Key, Value) => (String, [String])であり、ソートすると[(Key, Value)] =が返されます。 > [(文字列, [文字列])] . そして、それはあなたが得るものです。

または、識別子としてキーを持つ構造体またはクラス型を作成し、値を他のプロパティにすることもできます。次に、配列に追加できます。

上記のデータを使用してセクション化されたテーブルビューを作成する方法の例を次に示します。

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

上記の例は、それを行う方法を示しているだけです。すべてのテーブルビュー cellForRowAtIndexPath メソッドでソートし、各データ ソース メソッドで何らかの計算を行うため、パフォーマンスが良くありません。あなたはそれを自分で改良することができます:)

于 2015-09-03T19:44:31.933 に答える