Swift 3 - 数组映射.根据关系在数组中添加占位符值 [英] Swift 3 - Array mapping. Add placeholder values in array based on relationship
问题描述
我的第一个数组是:
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"]
我还需要在 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屋!