在我的项目中,我要从选择器视图中选择月份,然后在“文本”字段中放置月份名称。但是我必须将月号发送到服务器。
这是我的月份数组
var monthsArray = ["JANUARY","FEBRUARY","MARCH","APRIL","MAY","JUNE","JULY","AUGUST","SEPTEMBER","OCTOBER","NOVEMBER","DECEMBER"]
在这里我遇到了问题。例如,如果我选择“四月”,我必须将4发送到服务器,如何执行此任务,请有人帮忙/为我提供建议。
答案 0 :(得分:2)
如果具有文本值,只需在数组中找到该值的索引,然后加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
}
答案 1 :(得分:1)
类似的功能可能会帮助
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()”中非常重要,这将有助于识别所有情况下的月份,例如“一月”,“一月”或“一月”