swift 1.2 if循环到switch语句

swift 1.2 if loop to switch statement

我有以下 If 语句,我想知道如何使用 switch 语句实现它?

我试图将数组中的整数值表示为字符串(例如 1 == "Jan")

func assigningMonthName([Data]) {
    for i in dataset.arrayOfDataStructures {
        if (i.month) == 1 {
            println("Jan")
        }
        else if (i.month) == 2 {
            print("Feb")
        }
        else if (i.month) == 3 {
            print("March")
        }
        else if (i.month) == 4 {
            print("April")
        }
        else if (i.month) == 5 {
            print("May")
        }
        else if (i.month) == 6 {
            print("June")
        }
        else if (i.month) == 7 {
            print("July")
        }
        else if (i.month) == 8 {
            print("August")
        }
        else if (i.month) == 9 {
            print("September")
        }
        else if (i.month) == 10 {
            print("October")
        }
        else if (i.month) == 11 {
            print("November")
        }
        else if (i.month) == 12 {
            print("December")
        }
        else {
            println("Error assigning month name")
        }
    }

}

任何答案将不胜感激:)

试试这个:

switch i.month {
    case 1:
        print("Jan")
    case 2:
        print("Feb")
    ...
    default:
        print("default value")
}

虽然您可以使用 switch,但这本质上只是另一种编写 if-else 的方式,因此您的代码没有大的改进:

switch i.month {
    case 1:
        print("Jan")
    case 2:
        print("Feb")
    ...
}

使用数组怎么样?

let monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "Sept", "October", "November", "December"]
print(monthNames[i.month - 1])

系统实际上已经包含月份名称,它们甚至是本地化的:

let monthNames = NSDateFormatter().monthSymbols;
print(monthNames[i.month - 1])