【发布时间】:2019-11-08 02:35:55
【问题描述】:
我正在实现 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个case都写在代码里效率太低了。
你能让这个函数简单吗? 而不是编码所有 128 个案例,
【问题讨论】:
-
首先,您需要确定转换后的字符串是如何创建的(考虑边缘情况)。然后,您可以使用按位运算符来确定安排了哪些日期并基于此构造字符串。绝对不要创建 128 个案例语句!