快速-一周中的8天数据

时间:2018-07-24 14:33:13

标签: swift

从下面的8位开始,我想了解哪些日子是活跃的。 但是我无法提出适当的解决方案。

0b00101101
   |     |
   |     Monday
   Sunday

我尝试过的是:

func getWorkingDays(_ value: Data?) -> String? {
    guard let value = value else { return nil }
    if value.count == 1 {
        let days = calculateDays(value[0])
        return days
    }
    return nil
}

func calculateDays(_ days: UInt8?) -> String? {
        switch days {
        case 1:
            return "Monday"
        case 2:
            return "Tuesday"
        case 3:
            return "Monday, Tuesday"
        case 4:
            return "Wednesday"
        ......
}

2 个答案:

答案 0 :(得分:0)

您想使用OptionSet

  

您使用OptionSet协议表示比特集类型,其中各个比特代表集合的成员。

对于您来说,它看起来像这样。

struct Weekdays: OptionSet {
    let rawValue: Int

    static let monday    = Weekdays(rawValue: 1 << 0)
    static let tuesday   = Weekdays(rawValue: 1 << 1)
    static let wednesday = Weekdays(rawValue: 1 << 2)
    static let thrusday  = Weekdays(rawValue: 1 << 3)
    static let friday    = Weekdays(rawValue: 1 << 4)
    static let saturday  = Weekdays(rawValue: 1 << 5)
    static let sunday    = Weekdays(rawValue: 1 << 6)
}

然后将您从Int转换为Weekdays

let data = 0b00101101
let weekdays = Weekdays(rawValue: data)

并检查是否包含某天或几天?

if weekdays.contains(.monday) {
    print("It's monday!")
}

答案 1 :(得分:0)

一种简单的解决方案,它将位按右移,屏蔽除最右边的所有位,然后检查它是否为1或0,然后通过循环索引从数组中获取工作日名称。

例如

i = 00b00101101→索引0(星期一)。
i = 10b00010110
i = 20b00001011→索引2(星期三)


let weekdays = Calendar.current.weekdaySymbols // starts with `Sunday` will be adjusted with (i+1)%7

let activeDays = 0b00101101

var activeWeekdays = [String]()
for i in 0..<7 {
    if activeDays >> i & 0x1 == 1 { activeWeekdays.append(weekdays[(i + 1) % 7]) }
}
print(activeWeekdays) // ["Monday", "Wednesday", "Thursday", "Saturday"]