1

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.

2
  • 2
    You could do your own String as a date/time parsing, but you should consider looking at the available existing date and time APIs; see e.g. Date and DateFormatter. Commented Dec 13, 2016 at 8:21
  • 1
    Why don't you parse your date (they look all the same) and get the date components (month or date) from the resultng date? Commented Dec 13, 2016 at 8:23

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

I did something very similar to this as suggested by Leo and drfi, but will mark yours as the accepted answer

Your Answer

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.