从另一个过滤数组

时间:2017-05-27 10:07:36

标签: arrays swift filter

"是否可以删除for .. in(使其更加流畅)?

let arr1 = ["Bill", "John", "Richard", "Donald", "George"]
let arr2 = ["ill", "ck", "rd", "ld"]
var arr3 = Array<String>()

for str in arr2
{
    arr3 += arr1.filter{ $0.hasSuffix(str) }
}
debugPrint(arr3) // ["Bill", "Richard", "Donald"]

谢谢!

2 个答案:

答案 0 :(得分:0)

是的。将map函数与flatMap结合使用。如果你不想加倍(例如当后缀是&#34; d&#34;)时,使用Set():

let names = ["Bill", "John", "Richard", "Donald", "George"]
let suffixes = ["ill", "ck", "rd", "ld", "d"]
let namesWithSuffixes = Set(suffixes.map({ suffix in names.filter({ name in name.hasSuffix(suffix) }) }).flatMap({ $0 }))

但是如果你只是想摆脱旧的for循环,你可以使用forEach():

var arr3 = [String]()
suffixes.forEach({ suffix in
    arr3 += names.filter({ $0.hasSuffix(suffix) })
})

请注意,您的原始解决方案和第二个解决方案仅导致24次执行,而且#34; swifty&#34; map.filter.flatmap使用了29次执行。

enter image description here

答案 1 :(得分:0)

这不是更简洁明了吗?

arr3 = arr1.filter{name in arr2.contains{name.hasSuffix($0)}}