2015-10-19 196 views
1

我有以下If-Statment,我想知道如何通过switch语句实现这一点?swift 1.2如果循环切换语句

我试图表示在阵列中的整数值作为一个字符串(例如,1 ==“一月”)

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") 
     } 
    } 

} 

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

+0

只是一个建议,找到一种方法,通过使用'NSDate'从诠释得一个月。它会让你的生活比使用'if else'或'switch case'更容易 – t4nhpt

回答

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]) 
+0

谢谢!这很有意义。如果我想插入写月份,我在arrayofdatastructures内创建了一个名为'monthValue'的空字符串。我试着'i.monthName.insert(monthNames [i.month - 1])''但是我得到错误'不可变的值类型字符串只有变异成员名为插入' –

+1

@JessMurray这是一个有点不同的问题。可能你想要创建一个新的字符串(例如使用'String(format:...)'并且分配它来代替已经存在的字符串。 – Sulthan

1

试试:

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