get the first letter of every calendar month in swift

One way to achieve this is by using the DateFormatter class to format the month name and then taking the first letter of the resulting string. Here's an example:

main.swift
let calendar = Calendar.current
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMM"

for month in 1...12 {
    guard let date = calendar.date(from: DateComponents(month: month)),
          let monthName = dateFormatter.string(from: date).first else {
        continue
    }
    print(monthName)
}
314 chars
12 lines

In this code, we create a Calendar instance to get the dates for each month. Then, we create a DateFormatter with a date format string of "MMM", which represents the abbreviated month name. We loop over the numbers from 1 to 12, and for each number, we use Calendar to create a Date instance representing that month. We then format the month name using our DateFormatter and take the first letter of the resulting string using the first property.

The output of this code would be the first letter of each month's name:

main.swift
J
F
M
A
M
J
J
A
S
O
N
D
24 chars
13 lines

gistlibby LogSnag