使用“地图”在Swift中创建两个阵列的超集 [英] Using "Map" in Swift To Create Superset of Two Arrays

查看:81
本文介绍了使用“地图”在Swift中创建两个阵列的超集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有两个数组:

let letterArray = ["a", "b", "c", "d", "e"...]
let numberArray = [1, 2, 3, 4, 5, 6, 7...]

我想合并两个数组,以便得到

I want to combine the two arrays so that I would get an output of

["a1", "b2", "c3", "d4", "e5"]

我该如何做?

推荐答案

你可以使用 zip(_:在地图之前_:)

You can use zip(_:_:) before map:

let a = ["a", "b", "c", "d", "e"]
let b = [1, 2, 3, 4, 5]

let result = zip(a, b).map{$0 + String($1)}

print(result) // => ["a1", "b2", "c3", "d4", "e5"]

您可以在此处试用此代码。

zip(_:_:) 生成自定义 Zip2Sequence ,它具有 SequenceType 协议,以便它迭代从两个源集合中生成的对。

zip(_:_:) produces a custom Zip2Sequence, which has a special implmentation of the SequenceType protocol, so that it iterates pairs made from the two source collections.

这篇关于使用“地图”在Swift中创建两个阵列的超集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆