2015-10-19 189 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") 
}