Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Convert elements in an array of Int to elements of another array of String using map and filter

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading