Search code examples
arraysswiftboolean-operations

Bool array and corresponding title array in Swift



I have and array of bool values and array of titles and a string array, that have to show the users which product/s they selected.
array1 = ["false","true","false"]

array2 = ["apples","bananas","coconuts"]

selectedProducts[String] = []

I need to check if array1 have some "true" inside, and later retrieve it's index and append the product name at the same index to the selectedProducts.
User can select all of them, some of them or none.
Maybe connecting indexes of array1 and array2 is a bad decision.
I check is !array1.isEmpty but then I have 0 idea how to make this work.
Thank you

Solution

  • 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 }.