我有一组字典,[[String:AnyObject]]
,可以成功地按如下所示进行reduce +排序。
var arrUserList = [(key: String, value: [[String : Any]])]()
let result = self.arrJsonDict.reduce(into: [String: [[String:Any]]]()) { result, element in
let strName: String = (element as! NSDictionary).value(forKey: "name") as! String
if let firstLetter = strName.first {
let initial = String(describing: firstLetter).uppercased()
result[initial, default: [[String:Any]]() ].append(element as! [String : Any])
}}.sorted { return $0.key < $1.key }
self.arrUserList = result
现在,我想将键分配给表节和值作为数组中的表单元格文本。
答案 0 :(得分:4)
这是非常麻烦的代码。
强烈建议您至少与成员name
struct Person {
let name : String
}
声明arrJsonDic
并将其重命名为
var people : [Person]()
和arrUserList
为
var users = [String: [Person]]()
对于这些部分,声明另一个数组
var letters = [String]()
对数组进行分组,并简单地使用
填充letters
users = Dictionary(grouping: people, by: { String($0.name.first!) })
letters = users.keys.sorted()
在numberOfSections
中的表视图中返回
return letters.count
并在numberOfRows
中返回
let letter = letters[section]
return users[letter]!.count
在cellForRowAt
中,使用
let letter = letters[indexPath.section]
let user = users[letter]![indexPath.row]
cell.nameLabel.text = user.name
要使其保持 swiftier 声明第二个结构Section
struct Section {
let index : String
let people : [Person]
}
删除
var letters = [String]()
并声明users
var users = [Section]()
分组略有不同
let grouped = Dictionary(grouping: people, by: { String($0.name.first!) })
users = grouped.map({ Section(index: $0.0, people: $0.1) }).sorted{$0.index < $1.index}
三个表视图委托方法中的代码是
return users.count
-
return users[section].people.count
-
let user = users[indexPath.section].people[indexPath.row]
cell.nameLabel.text = user.name