How to iterate through an array of Strings and get the substring in Swift?

1.4k views Asked by At

First off, I feel my requirements are different, which is why I ask this question, but mark duplicate if necessary.

Now, I currently have an array of strings like so:

["January 27, 5:00PM - 10:00PM", "February 28, 11:00AM - 10:00PM", "March 29, 11:00AM - 9:00PM"]

I know how to extract just the date part of each index like so:

for index in 0..<array.count
{
    if let range = array[index].range(of: ",")
    {
        date = array[index][array[index].startIndex..<range.lowerBound]
    }
}

Result: January 27, February 28, March 29

My question is, how can I loop through the array and extract just the first 3 characters of the month, storing that in var1, then extracting the day, storing that in var2, all in one go in a clean and efficient way?

I know I can achieve something like this:

for index in 0..<array.count
{
    if let range = array[index].range(of: ",")
    {
        date = array[index][array[index].startIndex..<range.lowerBound]

        let nextArray = date.components(separatedBy: " ")

        let month = nextArray[0]
        let day = nextArray[1]
    }
}

Results: month = January, day = 27, etc..

However, I feel this is just messy, and not clean. Plus, I still need to extract the first 3 characters from the month.

1

There are 1 answers

1
Twitter khuong291 On BEST ANSWER

Try this:

var months = [String]()
var days = [String]()
var array = ["January 27, 5:00PM - 10:00PM", "February 28, 11:00AM - 10:00PM", "March 29, 11:00AM - 9:00PM"]

array.forEach() {
    let monthAndDay = $0.components(separatedBy: ",")

    let dateFormatter = DateFormatter()

    dateFormatter.dateFormat = "MMM dd"
    let date = dateFormatter.date(from: monthAndDay.first!)

    let dateFormatterMonth = DateFormatter()
    dateFormatterMonth.dateFormat = "MMM"
    months.append(dateFormatterMonth.string(from: date!))

    let dateFormatterDay = DateFormatter()
    dateFormatterDay.dateFormat = "dd"
    days.append(dateFormatterDay.string(from: date!))
}

print(months) // Jan, Fer, Mar
print(days) // 27, 28, 29