如何在swift中将月份名称数组转换为月份数字
如何在swift中将月份名称数组转换为月份数字
此问题已有答案:
在我的项目中,我从选择器选择月份,将月份名称放置在文本字段中。但是我必须向服务器发送月份编号。
这是我的月份数组
var monthsArray = ["JANUARY","FEBRUARY","MARCH","APRIL","MAY","JUNE","JULY","AUGUST","SEPTEMBER","OCTOBER","NOVEMBER","DECEMBER"]
在这里,我遇到了一个问题。例如,如果我选择了四月,我必须将4发送到服务器,如何完成此任务,请有人帮助/建议我。
admin 更改状态以发布 2023年5月20日
这样的函数可能会有所帮助
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 }
其可以如下使用:
var idx = getMonthIndex("January") //1 idx = getMonthIndex("JANUARY") //1 idx = getMonthIndex("DECEMBER") //12 idx = getMonthIndex("DECEMBERRRR") //-1
在上面的片段中,“month.uppercased()”非常重要,这将有助于识别所有情况下的月份,例如“January”、“JANUARY”或“january”。
如果你有文本值,只需要在数组中找到该值的索引,然后再加1(因为数组以零为基础)
类似这样的代码应该可以工作:
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 }