通过Swift中的开头字符将数组拆分为多维数组?

时间:2016-01-17 03:47:48

标签: arrays swift multidimensional-array

例如,我想要数组

["ABC", "ADE", "BCD", "HYD", "ZYX", "ZZZ"]

转换为:

[
    ["ABC", "ADE"],
    ["BCD"],
    ["HYD"],
    ["ZYX", "ZZZ"],
]

那我怎么能做到这一点?谢谢!

1 个答案:

答案 0 :(得分:4)

使用你的数组创建一个中间字典,将首字母映射到以该字母开头的字符串数组,然后从字典中创建最终数组:

let arr = ["ABC", "ADE", "BCD", "HYD", "ZYX", "ZZZ"]

var dict = [Character:[String]]()

for str in arr {
    if let first = str.characters.first {
        dict[first] = (dict[first] ?? []) + [str]
    }
}

print(dict) // ["H": ["HYD"], "B": ["BCD"], "A": ["ABC", "ADE"], "Z": ["ZYX", "ZZZ"]] 

let arr2 = dict.keys.sort().map { dict[$0]! }
print(arr2) // [["ABC", "ADE"], ["BCD"], ["HYD"], ["ZYX", "ZZZ"]]