gpt4 book ai didi

ios - 关于 Swift 中 iPhone 闹钟应用程序中日期重复功能的问题

转载 作者:行者123 更新时间:2023-11-28 13:23:23 24 4
gpt4 key购买 nike

我正在实现 iPhone 闹钟应用的日间重复功能。

我想用Bitmask来设置星期一(1)、星期二(2)、星期三(4)、星期四(8)、星期五(16)、星期六(32)、星期日(64)和星期几.

当我使用这个方法时,我得到了 0 ~ 127, 128 天设置的组合。

fileprivate func convertSchedule(_ schedule: Int) -> String {
switch schedule {
case 0: return "none"
case 1: return "Every Monday"
case 2: return "Every Tuesday"
case 3: return "mon,tue"
case 4: return "Every Wednesday"
case 5: return "mon,wed"
case 6: return "tue,wed"
default: break
}
return ""
}

此代码将 0 到 127 之间的数字转换为星期几字符串。我认为将 128 个案例都写在代码中效率太低了。

你能把这个功能简单化吗?而不是对所有 128 个案例进行编码,

最佳答案

您在位掩码方面走在正确的轨道上。您可以从时间表中提取要重复的天数,然后根据天数构造字符串。例如,你可以引用我下面的例子:

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: ",")
}
}

关于ios - 关于 Swift 中 iPhone 闹钟应用程序中日期重复功能的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58759593/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com