如果我知道当天的情况,如何确定一周的下一天?

问题描述 投票:0回答:1

我创建了一个天气应用程序,为此我使用了API。 (我使用OpenWeatherMap和API作为“Call 5天/ 3小时预测数据”)我获得了所需的所有信息。

然后我得到了一周中所有日子的数据。例如,星期一临时22度,星期二临时12度等。

我可以获得当周的当天并添加到字典中。

但我无法获得新的dayName(星期几)。我需要做什么?我需要帮助获取一周中的下几天及其索引的名称。然后将键值添加到字典中。

// Indexed all days of the week Sun, Mon, Wed and a t.c             
let setWeekDay = IndexSet([1, 2, 3, 4, 5, 6, 7]) 

//I detected current day of the weak and added to dictionary
var weakDay = [String:Int]()
let calendar = Calendar.current
var weekday =  calendar.component(.weekday, from: Date())
let components = DateComponents(weekday: weekday)

var dayName = calendar.nextDate(after: Date(), matching: components, matchingPolicy: .nextTime)?.Days()

weakDay = [dayName!:weekday]

if let nextWeekday = setWeekDay.integerGreaterThan(weekday) {
    weekday = nextWeekday
    } else {
        weekday = setWeekDay.first!
    }


...
// I extended date formatter
extension Date{
    func Days() -> String{
        let dataFormatter = DateFormatter()
        dataFormatter.dateStyle = .short
        dataFormatter.dateFormat = "EEEE"
        return dataFormatter.string(from: self)
    }
}

//This is dictionary will be change key and value dynamically.

//I need got dictionary as:
let weakDay = [
                "Sunday": 1,
                "Monday": 2,
                "Tuesday": 3,
                "Wednesday": 4,
                "Thursday": 5,
                "Friday": 6,
                "Saturday": 7,
                ]
swift calendar nsdatecomponents
1个回答
0
投票

感谢所有人的帮助,但我自己找到了回答我的问题!我需要做的是:

if let cell = tableView.dequeueReusableCell(withIdentifier: "daysId", for: indexPath) as? DaysTVCell {

            var nameWeakAndIndex = [String:Int]()

            var dateComponents = DateComponents()
            dateComponents.setValue(1, for: .day);
            var now = Date()

            for index in 0...5 {

                let tomorrow = Calendar.current.date(byAdding: dateComponents, to: now)

                let detectDayIndex = index

                nameWeakAndIndex = [now.Days():detectDayIndex]

                now = tomorrow!

                daysWeak.sort(by: { (nameWeakAndIndex[$0.dayOfTheWeak] ?? 6) > (nameWeakAndIndex[$1.dayOfTheWeak] ?? 6) })
            }


            let day = daysWeak[indexPath.row]
            cell.configureCell(daysForecast: day)
            return cell
© www.soinside.com 2019 - 2024. All rights reserved.