arrays - 在 Swift 5 中,如何有效地提取和使用多维数组中的元素?
问题描述
这是我第 5 天使用 swift/xcode 编程的新手,请善待。
我创建了一个格式为 - [[A], [B], [C], [D], [E], [F]], ... 的数组作为查找表。要求是获取A - AM/PM 和B、C - 开始时间并检查当前时间(小时、分钟)是否在D、E - 结束时间的范围内,如果是,则在 UILabel 上打印消息 F。
例如,如果现在是凌晨 3.04,我的程序将使用下表打印“去睡觉,我会在 4 点通知你”
// [[A], [B], [C], [D], [E], [F]], ...
let messageArray : Array = [
[["AM"], [00], [00], [00], [01], ["it's \nmidnight"]],
[["AM"], [00], [02], [02], [59], ["it's very late (or early), \nto be up"]],
[["AM"], [03], [00], [03], [01], ["are you ready \nfor the 03 am call?"]],
[["AM"], [03], [02], [03], [59], ["go to sleep \ni'll let you know when it's \n4"]],...
我知道如何从当前时间获取小时和分钟。
let date = Date()
var calendar = Calendar.current
let hour = calendar.component(.hour, from: date)
let minute = calendar.component(.minute, from: date)
并且我需要一个外部和内部循环来遍历矩阵的每个 x,y。对于每个单元格,我需要提取数组并获取前 4 个元素 - AM/PM、startHour、startMinute、endHour、endMinute 以检查当前小时、分钟是否在这些范围内;但我不确定我是否理解多维数组解析。我尝试了各种方法并尝试在网上查找,但我很挣扎。
我什至应该为此使用数组,还有其他更有效的数据结构吗?
任何帮助或建议将不胜感激。
谢谢,
解决方案
使用 [(Hour, Minute):String] 类型的字典
let hour = Calendar.current.component(.hour, from: Date())
let minute = Calendar.current.component(.minute, from: Date())
let messageArray: [(Int, Int):String] = [
(0, 1): ["it's\nmidnight"],
(2, 59): ["it's\very early"],
(3, 01): ["that 3am call?"],
(3, 59): ["come back at 4"]
]
然后您可以使用函数式编程来检查订单。
extension Dictionary where Key == (Int, Int) {
func smallestValue<T: Value>(_ time: (Int, Int)) -> T? {
let message: T? = nil
for i in self {
// Check for smallest case that is good
}
return message
}
}
let message = messageArray.smallestValue((hour, minute)) ?? "Good job for being awake"
print(message)
可能需要为 (Int, Int) 建立一个结构
推荐阅读
- mysql - str_to_date(date_format(sysdate(),'%d-%b-%Y'),'%d-%b-%Y')-max(ren_date)>=7 附近的语法错误
- vba - 在特定工作表中传输特定行中的数据
- tfs-2015 - TFS 2015 映射问题,例如禁用的本地路径
- javascript - 从 Javascript 中的 JWT 中提取“角色”
- vba - 突出显示行直到特定列
- java - Java 计数分配
- javascript - 我得到 [1,15],而不是 [1,0,15]。JavaScript 过滤器
- php - 无法使用php从excel文件中读取每列和每行的记录
- reactjs - 在解决方案中添加反应项目
- python - Python - 如何在 Fabric 模块中设置 env.variables