首页 > 解决方案 > 在 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 以检查当前小时、分钟是否在这些范围内;但我不确定我是否理解多维数组解析。我尝试了各种方法并尝试在网上查找,但我很挣扎。

我什至应该为此使用数组,还有其他更有效的数据结构吗?

任何帮助或建议将不胜感激。

谢谢,

标签: arraysswiftmultidimensional-arraytime

解决方案


使用 [(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) 建立一个结构


推荐阅读