0

I have an array of strings with a large amount of data, only some of which I want. I'm separating the good data using a separator like:

var result = contentArray[1].components(separatedBy: ",")

This leaves me with garbage data in even number indices of the result array, and good data in odd numbered indices.

Now I'm only wanting to work with the good data to make things simple later on. I can do that by creating another array using a for in loop with stride...

But this seems like at least one extra step. Is there a way I can sort the data in the first array without creating 2 arrays? This would have the app creating 3 arrays with large amounts of data when it seems like I should be able to do it in 1 or 2. I'm planning on doing this with a minimum of 20 data sets so that seems a lot of extra arrays in memory

asked May 15, 2017 at 15:56
3
  • 1
    Why optimize prematurely? My suggestion is to get it working first, run some performance tests, and optimize only if needed. Commented May 15, 2017 at 16:00
  • 1
    @nathan good point. I do tend to fret a bit early on. Why do extra work when I don't have to? brilliant Commented May 15, 2017 at 16:06
  • Keep in mind most of the base Swift types are copy-on-mutate. If you don't change the actual data you're likely only making additional references (small footprint) and not actually copying all the data. Commented May 15, 2017 at 16:49

1 Answer 1

1

You can go like this.

let filterArray = result.indices.flatMap { 0ドル % 2 != 0 ? nil : result[0ドル] }
print(filterArray)

Edit: If you want to store output of filter in same array try like this.

var result = contentArray[1].components(separatedBy: ",")
result = result.indices.flatMap { 0ドル % 2 != 0 ? nil : result[0ドル] }
print(result)
answered May 15, 2017 at 16:02
4
  • 1
    Isn't that just creating a 3rd array which is what I would like to avoid? Commented May 15, 2017 at 16:03
  • thanks, that looks great. I'm not familiar with flatMap syntax, and the compiler is throwing use of unresolved identifier array (pointing at: array[0ドル]) Commented May 15, 2017 at 16:17
  • @froggomad actually you need to populate result array for so simply make it mutable by declaring it with var instead of let check the edited answer Commented May 15, 2017 at 16:20
  • I see, great thanks. I'm looking into tutorials now to see if I can do it when creating the first array so I'm only creating 1 array in total Commented May 15, 2017 at 16:24

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.