我使用选项集
创建了SchedulePicker在那之后,我还创建了一个函数,该函数将天数从0转换为127 转换为字符串。
struct WeekDay {
let rawValue: Int
let name: String
static let mon = WeekDay(rawValue: 1, name: "Monday")
static let tue = WeekDay(rawValue: 1<<1, name: "Tuesday")
static let wed = WeekDay(rawValue: 1<<2, name: "Wednesday")
static let thu = WeekDay(rawValue: 1<<3, name: "Thursday")
static let fri = WeekDay(rawValue: 1<<4, name: "Friday")
static let sat = WeekDay(rawValue: 1<<5, name: "Saturday")
static let sun = WeekDay(rawValue: 1<<6, name: "Sunday")
static let all: [WeekDay] = [.mon, .tue, .wed, .thu, .fri, .sat, .sun]
func isIncluded(in schedule: Int) -> Bool {
return schedule & rawValue == rawValue
}
}
fileprivate func convertSchedule(_ schedule: Int) -> String {
var daysToRepeat = WeekDay.all.filter({ $0.isIncluded(in: schedule) })
if daysToRepeat.count == 0 {
return "none"
} else if daysToRepeat.count == 1 {
return "Every \(daysToRepeat[0].name)"
} else {
return daysToRepeat.map({ $0.name }).joined(separator: ",")
}
}
现在我需要为weekday
创建一个DateComponents ()
工作日包括1 =星期日至7 =星期六。
如何在DateComponents()
中映射128个 SchedulePicker 案例和工作日?
答案 0 :(得分:1)
我想知道问题是否不是代表制的最初选择。我会做这样的事情:
enum Weekday : Int, CaseIterable {
case mon = 1
case tue
case wed
case thu
case fri
case sat
case sun
var name : String {
let greg = Calendar(identifier: .gregorian)
let dayNames = greg.weekdaySymbols
return dayNames[self.rawValue]
}
}
这使得处理信息非常容易:
let weekdaysChosen : [Weekday] = [.mon, .tue, .fri] // example
let namesOfWeekdays = weekdaysChosen.map{$0.name}.joined(separator: ", ")
print(namesOfWeekdays) // "Mon, Tue, Fri"
let numbersOfWeekdays = weekdaysChosen.map{$0.rawValue}
print(numbersOfWeekdays) // [1, 2, 5]