SWIFT 5.1合并2个不同数据类型的数组?

时间:2019-11-13 06:48:53

标签: arrays swift array-merge

对于SWIFT 5.1

如何获取字符串数组以与整数数组合并?

stringArray:[“ Tom”,“ Dick”,“ Harry”]

intArray:[1,2,3]

我正在寻找的结果是一个格式为String:Int

的列表

汤姆:1

迪克:2

哈里:3

2 个答案:

答案 0 :(得分:2)

要实现此目的,您必须链接一些很棒的高阶函数,如下所示:

let name = ["Tom", "Dick", "Harry"]

let id = [ 1, 2, 3]

let dict = zip(name, id).map { [$0.0 : $0.1] }
                        .reduce([:]) { $0.merging($1) { (current, _) in current } }

print(dict)

答案 1 :(得分:0)

这可以通过以下方式完成:

var intOne: [Int] = [1, 2, 3, 4]
var stringArray: [String] = ["a","b","c","d"]

var dictionary: [Int: String] = [:]

for (index, element) in intOne.enumerated() {
    dictionary[element] = stringArray[index]
}

print(dictionary)
Output: [2: "b", 3: "c", 1: "a", 4: "d"]


extension Dictionary {
    public init(keys: [Key], values: [Value]) {
        precondition(keys.count == values.count)

        self.init()

        for (index, key) in keys.enumerated() {
            self[key] = values[index]
        }
    }
}