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
-
1Why optimize prematurely? My suggestion is to get it working first, run some performance tests, and optimize only if needed.nathangitter– nathangitter2017年05月15日 16:00:31 +00:00Commented 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? brilliantfroggomad– froggomad2017年05月15日 16:06:42 +00:00Commented 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.GetSwifty– GetSwifty2017年05月15日 16:49:43 +00:00Commented May 15, 2017 at 16:49
1 Answer 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)
-
1Isn't that just creating a 3rd array which is what I would like to avoid?froggomad– froggomad2017年05月15日 16:03:22 +00:00Commented 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ドル])froggomad– froggomad2017年05月15日 16:17:44 +00:00Commented 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 oflet
check the edited answerNirav D– Nirav D2017年05月15日 16:20:51 +00:00Commented 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 totalfroggomad– froggomad2017年05月15日 16:24:06 +00:00Commented May 15, 2017 at 16:24