您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

将项作为字典值添加到数组

将项作为字典值添加到数组

您可以使用reduce(into:)方法(Swift4),如下所示:

let contacts = ["Aaron", "Adam", "Brian", "Brittany", ""]
let dictionary = contacts.reduce(into: [String:[String]]()) { result, element in
    // make sure there is at least one letter in your string else return
    guard let first = element.first else { return }
    // create a string with that initial
    let initial = String(first)
    // initialize an array with one element or add another element to the existing value
    result[initial] = (result[initial] ?? []) + [element]
}
print(dictionary)   // ["B": ["Brian", "Brittany"], "A": ["Aaron", "Adam"]]

如果您使用的是Swift3或更早版本,则需要在闭包内部创建一个可变的结果字典:

let contacts = ["Aaron", "Adam", "Brian", "Brittany", ""]
let dictionary = contacts.reduce([String:[String]]()) { result, element in
    var result = result
    guard let first = element.first else { return result }
    let initial = String(first)
    result[initial] = (result[initial] ?? []) + [element]
    return result 
}
print(dictionary)   // ["B": ["Brian", "Brittany"], "A": ["Aaron", "Adam"]]

请注意,结果未排序。字典是无序集合。如果需要对字典进行排序并返回(键,值)元组的数组,则可以按以下方式使用按键排序:

let sorted = dictionary.sorted {$0.key < $1.key}
print(sorted)

“ [[(键:” A“,值:[” Aaron“,”亚当“]),(键:” B“,值:[” Brian“,” Brittany“])] \ n”

其他 2022/1/1 18:13:46 有521人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶