Advertisements
I have an array of integers var array: [Int] = [0, 1, 2]
I have an array of strings var arrayOfStrings: [String] = ["apple", "banana", "orange"]
I have a function that i can pass an array parameter of Int and returns an array of String.
If i call the function and pass the following Int array [0, 1] which means that the user selected apple and banana, i need to return from that function the array of string with apple and banana from the second array which means ["apple", "banana"]. How is this possible using map and filter in swift? Any help appreciated.
>Solution :
First you don’t need the first array. You should always use the original array indices.
let array = arrayOfStrings.indices // note that it is a Range not an array
You just need to iterate the selected indices and map the original array:
let selectedIndices: [Int] = [0, 1]
let selectedElements = selectedIndices.indices.map { arrayOfStrings[$0] }
selectedElements