Swift 3-数组映射。根据关系在数组中添加占位符值 [英] Swift 3 - Array mapping. Add placeholder values in array based on relationship

查看:118
本文介绍了Swift 3-数组映射。根据关系在数组中添加占位符值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的第一个数组是:

arr1 = [1, 2, 3, 4, 5]

我的第二个数组是:

arr2 = [2, 3, 4]

我的第三个数组是:

arr3 = ["2a", "3a", "4a"]

arr2和arr3与索引值相关,即arr2 [0]与arr3 [0]相关,与[1]和[2]相同。

arr2 and arr3 are related by index values, i.e., arr2[0] relates to arr3[0], same for [1] and [2].

我已经能够将arr2与arr1进行比较并添加占位符值,因此我的占位符数组为

I have been able to compare arr2 against arr1 and add placeholder values so my placeholder array for them is

arr1to2 = ["No match", 2, 3, 4, "No Match"]

现在我需要将arr3与arr2与arr1(或者arr1to2)进行比较,因此我的输出应该是

Now I need to compare arr3 against arr2 to arr1 (alternatively arr1to2), so my output should be

array_final = ["No match", 2a, 3a, 4a, "No match"]

I还需要保持array_final和arr1to2的索引值之间的关系。 [1]与[1],[2]至[2],[3]至[3]相关。

I need to have the relationship maintained between index values of array_final and arr1to2 as well. [1] relates [1], [2] to [2], [3] to [3].

推荐答案

您可以这样操作:

let arr1 = [1, 2, 3, 4, 5]
let arr2 = [2, 3, 4]
let arr3 = ["2a", "3a", "4a"]

// first lets join arr2 and arr3 to a dictionary
var dict: [Int: String] = [:]
zip(arr2, arr3).forEach({ (pair) in
    dict[pair.0] = pair.1
})

// and then just map each value in arr1 according to the dictionary, or provide a "No match" default
let result = arr1.map { (value) -> String in
    return dict[value] ?? "No match"
}

print(result)

这篇关于Swift 3-数组映射。根据关系在数组中添加占位符值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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