0

In my project, I am selecting months from picker view that month name is placed in Text field. But I have to send Month Number to the server.

This is my month array

var monthsArray = ["JANUARY","FEBRUARY","MARCH","APRIL","MAY","JUNE","JULY","AUGUST","SEPTEMBER","OCTOBER","NOVEMBER","DECEMBER"]

Here I am getting a problem. For an example If I select April, I have to send 4 to the server, How to do this task please someone help/ advise me.

Ram
  • 3
  • 2
  • 8

2 Answers2

2

If you have the text value, just find the index of that value in the array and then add 1 (because the array is zero index based)

Something like this should work:

var monthsArray = ["JANUARY","FEBRUARY","MARCH","APRIL","MAY","JUNE","JULY","AUGUST","SEPTEMBER","OCTOBER","NOVEMBER","DECEMBER"]
if let index = monthsArray.index(of: "APRIL") { // index will be 3 (zero based)
    let monthNumber = index + 1 // +1 as explained earlier
    print(monthNumber) // output: 4
}
Scriptable
  • 19,402
  • 5
  • 56
  • 72
1

A function like this may help

func getMonthIndex(_ month: String) -> Int {
    let months = ["JANUARY","FEBRUARY","MARCH","APRIL","MAY","JUNE","JULY","AUGUST","SEPTEMBER","OCTOBER","NOVEMBER","DECEMBER"]
    var monthIndex = -1
    if let idx = months.index(of: month.uppercased()) {
        monthIndex = idx + 1
    }
    return monthIndex
}

which can be used as follows :

var idx = getMonthIndex("January")  //1
idx = getMonthIndex("JANUARY") //1
idx = getMonthIndex("DECEMBER") //12
idx = getMonthIndex("DECEMBERRRR") //-1

In the snipped above "month.uppercased()" is very important this will help to identify months in all cases such as "January", "JANUARY" OR "january"

Rizwan
  • 3,324
  • 3
  • 17
  • 38