How to make alphabetically section headers in table view with a mutable data source

前端 未结 3 1340
一生所求
一生所求 2021-01-05 07:59

I store strings of a view controller in a string array. I import this string array as a Data Source in my table view. This all works smoothly. But now I would like to sort t

3条回答
  •  半阙折子戏
    2021-01-05 08:38

    For Swift 3. Thank you @Stefan! Here is my version with Set

    var tableViewSource: [Character : [String]]!
    var tableViewHeaders: [Character]!
    
    let data = ["Anton", "Anna", "John", "Caesar"]
    
    func createTableData(wordList: [String]) -> (firstSymbols: [Character], source: [Character : [String]]) {
    
        // Build Character Set
        var firstSymbols = Set()
    
        func getFirstSymbol(word: String) -> Character {
            return word[word.startIndex]
        }
    
        wordList.forEach {_ = firstSymbols.insert(getFirstSymbol(word: $0)) }
    
        // Build tableSourse array
        var tableViewSourse = [Character : [String]]()
    
        for symbol in firstSymbols {
    
            var words = [String]()
    
            for word in wordList {
                if symbol == getFirstSymbol(word: word) {
                    words.append(word)
                }
            }
    
            tableViewSourse[symbol] = words.sorted(by: {$0 < $1})
        }
    
        let sortedSymbols = firstSymbols.sorted(by: {$0 < $1})
    
        return (sortedSymbols, tableViewSourse)
    }
    
    func getTableData(words: [String]) {
        tableViewSource = createTableData(wordList: words).source
        tableViewHeaders = createTableData(wordList: words).firstSymbols
    }
    
    getTableData(words: data)
    
    print(tableViewSource)  // ["J": ["John"], "C": ["Caesar"], "A": ["Anna", "Anton"]]
    print(tableViewHeaders) // ["A", "C", "J"]
    

提交回复
热议问题