首页 > 解决方案 > `weekday` 是否保证在 [1:7] 范围内?

问题描述

我相信答案是肯定的,但 Apple 的文档暗示答案是否定的。

工作日单位是数字 1 到 n,其中 n 是一周中的天数。例如,在公历中,n 为 7,星期日由 1 表示。weekday

这句话似乎表明不同的日历系统有不同的周长。在对 Wikipedia 进行一些研究后,我找不到任何现代日历在n != 7.

我误读了这个吗?Foundation 中是否有任何周历在哪里n != 7

标签: iosdatecalendarfoundation

解决方案


这不一定是保证,但以下代码找不到任何没有除1..<8.

let calIds: [Calendar.Identifier] = [ .buddhist, .chinese, .coptic, .ethiopicAmeteAlem, .ethiopicAmeteMihret, .gregorian, .hebrew, .indian, .islamic, .islamicCivil, .islamicTabular, .islamicUmmAlQura, .iso8601, .japanese, .persian, .republicOfChina]
for calId in calIds {
    var cal = Calendar(identifier: calId)
    for locId in Locale.availableIdentifiers {
        let locale = Locale(identifier: locId)
        cal.locale = locale

        if let weekdayMin = cal.minimumRange(of: .weekday), let weekdayMax = cal.maximumRange(of: .weekday) {
            if weekdayMin == weekdayMax {
                if weekdayMin.startIndex != 1 || weekdayMin.count != 7 {
                    print("Calendar \(calId) with locale \(locId) isn't 1..<8: \(weekdayMin)")
                }
            } else {
                print("Calendar \(calId) with locale \(locId) has a different min and max weekday range: \(weekdayMin) - \(weekdayMax)")
            }
        } else {
            print("Calendar \(calId) with locale \(locId) doesn't have both a min and max weekday range")
        }
    }
}

推荐阅读