您正在打开Set<RepeatDay>,但案例是RepeatDay。 switch 语句无法知道您希望它如何处理这些不同的类型。
我怀疑您正在尝试匹配特定类型的天数集,例如工作日的天数集和周末的天数集。在这种情况下,您的 switch 的 case 语句需要为Set<RepeatDay,可以与提供的Set<RepeatDay> 进行比较。
switch days {
case [.Monday, .Tuesday, .Wednesday, .Thursday, .Friday]:
print("Weekdays")
case [.Saturday, .Sunday]:
print("Weekends")
default:
print(days)
}
我会将这些 case 语句的集合提取为 Day 枚举的静态成员,并添加更多逻辑来描述连续的天数间隔。您还可以从weekdaySymbols 的DateFormatter 获取天数的准确区域设置名称
import Foundation
extension Array where Element: Integer {
func isConsecutive() -> Bool {
guard var previous = self.first else { return true }
for current in self[1 ..< self.count] {
if current != previous + 1 { return false }
previous = current
}
return true
}
}
enum Day: Int, CustomStringConvertible {
case Sunday
case Monday
case Tuesday
case Wednesday
case Thursday
case Friday
case Saturday
/*TODO: Note that this stores the weekdaySymbols permanently once
the app is launched. If there is a change in locale after the app
launch, then the days will not be updated. If this is a concern,
this `DayNames` constant should be deleted, and all references
to it should be changed to DateFormatter().weekdaySymbols, which
will dynamically obtain the weekdays accurate to the current locale */
static let DayNames: [String] = DateFormatter().weekdaySymbols
public var description: String { return Day.DayNames[self.rawValue] }
static let Everyday: Set<Day> = [.Sunday, .Monday, .Tuesday, .Wednesday, .Thursday, .Friday, .Saturday]
static let Weekdays: Set<Day> = [.Monday, .Tuesday, .Wednesday, .Thursday, .Friday]
static let Weekends: Set<Day> = [.Saturday, .Sunday]
static func describeDays(_ days: Set<Day>) -> String {
guard days.count > 0 else { return "No days" }
switch days { // Predefined cases
case Day.Everyday: return "Everyday"
case Day.Weekdays: return "Weekdays"
case Day.Weekends: return "Weekends"
default: break
}
let array = days.map{ $0.rawValue }.sorted()
switch array {
case _ where array.isConsecutive(): // Consecutive range of days
let min = array.first!
let max = array.last!
return "\(Day(rawValue: min)!) - \(Day(rawValue: max)!)"
default: return days.description //arbitrary days
}
}
}
print(Day.describeDays(Day.Everyday))
print(Day.describeDays(Day.Weekdays))
print(Day.describeDays(Day.Weekends))
print(Day.describeDays([.Monday, .Tuesday, .Wednesday, .Thursday])) // Monday - Thursday
print(Day.describeDays([.Tuesday, .Wednesday, .Thursday, .Saturday])) //[Saturday, Wednesday, Thursday, Tuesday]
You can see this in action, here.