array1 = ["false","true","false"]
array2 = ["apples","bananas","coconuts"]
selectedProducts[String] = []
Use zip()
to combine the arrays and compactMap()
to select those values which are paired with true
:
let array1 = ["false","true","false"]
let array2 = ["apples","bananas","coconuts"]
let selectedProducts = zip(array1, array2).compactMap { $0 == "true" ? $1 : nil }
print(selectedProducts)
bananas
Note: If array1
contains Bool
instead of String
, then the closure passed to compactMap
could simply be { $0 ? $1 : nil }
.