swift 1.2 if loop to switch语句

时间:2015-10-19 07:45:04

标签: swift if-statement switch-statement

我有以下的If-Statment,我想知道如何通过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")
        }
    }

}

任何答案都将不胜感激:)

2 个答案:

答案 0 :(得分:2)

虽然您可以使用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])

答案 1 :(得分:1)

试试这个:

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