Home > Mobile >  Bool array and corresponding title array in Swift
Bool array and corresponding title array in Swift

Time:06-07


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

CodePudding user response:

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

CodePudding user response:

You can try

let res = array2.indices.compactmap { array1[$0] == "true" ? array2[$0] :  nil  }

While it's better to make it pure boolean

 array1 = [false,true,false]

Then

let res = array2.indices.compactmap { array1[$0] ? array2[$0] :  nil  }

BTW it's more better to make it a strcut/class item than having two arrays

struct Item {
   let name:String
   var isSelected:Bool
} 

Then

let arr = [Item]() // fill it with your data

Finally

let res = arr.filter { $0.isSelected  }
  • Related