gpt4 book ai didi

swift - 来自 8 位数据的一周中的几天

转载 作者:行者123 更新时间:2023-11-30 11:18:53 25 4
gpt4 key购买 nike

从下面的 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"
......
}

最佳答案

您想了解如何使用 OptionSet

You use the OptionSet protocol to represent bitset types, where individual bits represent members of a set.

在你的情况下,它看起来像这样。

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!")
}

关于swift - 来自 8 位数据的一周中的几天,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51501271/

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