-2

I have an array like:

["2018-03-21 11:09:25","2018-03-22 11:09:25","2018-03-23 11:09:25","2018-03-24 11:09:25"]

I need to display only dates [2018-03-21] in this array. How to split this array?

Jan Černý
  • 1,268
  • 2
  • 17
  • 31
ios dev
  • 13
  • 2

2 Answers2

1

Considering you have and want Strings, here is a way you could use with Swift 4:

var myArray = [String]()
for date in dateArray {

    myArray.append(date.split(" ")[0])

}
marc
  • 914
  • 6
  • 18
0

You have to split your task in subtasks to make it easy for you.

How to transform your data?

Given an your input 2018-03-21 11:09:25 and your ouput 2018-03-21, there are several ways.

I see 3 regular ways here (there are more of course):

  1. Splitting with the space character as a delimiter and take the first part
  2. Using a DateFormatter
  3. Using substring to the 10th character

As 2. seems overkill and 3. would need to work with ranges (I'm lazy), let's take 1. as an example:

let ouput = input.split(" ")[0]

How to apply to the whole array?

You have many options, again, but the simpler is map.

Given your initial array is called array.

Solution

let result = array.map { $0.split(" ")[0] }

Francescu
  • 16,974
  • 6
  • 49
  • 60