2017-03-17 54 views
0

致命錯誤:索引超出範圍withot使用任何陣列時,我使用循環致命錯誤:索引超出範圍,而無需使用任何陣列

func getDayOfWeek(_ today:String) -> String? { 
     let dateFormatter = DateFormatter() 
     dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ" 
     let date = dateFormatter.date(from:today) 
     let weekDay = dateFormatter.weekdaySymbols[Calendar.current.component(.weekday, from:date!)] 
     return weekDay 
    } 
+0

告訴你這段代碼 – Tj3n

+0

2017-03-20T04使用日期:13:00Z –

+1

顯示環 –

回答

1

Calendar.current.component(.weekday, from:date!)開始從1至7,但只有從0到6 weekdaySymbols的指數,所以你要減一,以獲得正確的工作日:

let weekDay = dateFormatter.weekdaySymbols[Calendar.current.component(.weekday, from:date!)-1] 

也應該使用if let和可選類似的其他答案建議,以避免崩潰

+0

工作的罰款只是不工作! –

0

這是一個數組轉換日期爲星期幾:

dateFormatter.weekdaySymbols

如果字符串格式錯誤,那麼'date'也可以爲零。您應該檢查這樣的:

func getDayOfWeek(_ today:String) -> String? { 
    let dateFormatter = DateFormatter() 
    dateFormatter.dateFormat = "yyyy-MM-dd" 
    if let date = dateFormatter.date(from:today) { 
     let weekDay = dateFormatter.weekdaySymbols[Calendar.current.component(.weekday, from:date)] 
     return weekDay 
    } 
    return nil 
} 
0

您可能需要將星期幾轉換爲星期索引!

let weekname = getWeekDayName(weekDay: calendar.component(.weekday, from: date())) 

func getWeekDayName(weekDay:Int) -> String 
{ 
    let f = DateFormatter() 
    let index:Int = (weekDay - 1) % 7 
    print("Week No: " + String(weekNo) + " No: " + String(index)) 
    let weekName = f.weekdaySymbols[index] 
    print("Week Name: " + weekName) 
    return weekName 
} 
相關問題