如何使用Swift 4从数组中分离日期与数值?
从Swift数组中分离日期与数值的解决方案
我来帮你搞定这个需求~首先看你的数据结构,arrWeekly是包含多个字典的数组,每个字典里包含date(字符串格式)、units和value(可能是Int或String类型),我们可以通过遍历数组+类型转换来分离出日期和数值。
核心实现代码
首先针对你的arrWeekly数组,直接分离的代码如下:
// 初始化两个数组,分别存储分离后的日期和数值 var separatedDates: [String] = [] var separatedValues: [Double] = [] // 遍历原数组,逐个处理每个元素 for item in arrWeekly { // 先将元素转为[String: Any]类型,确保是我们预期的字典结构 guard let weeklyItem = item as? [String: Any] else { continue // 如果不是字典类型,跳过当前元素避免崩溃 } // 提取日期并加入数组 if let date = weeklyItem["date"] as? String { separatedDates.append(date) } // 提取数值:兼容Int和String类型的value,统一转为Double if let value = weeklyItem["value"] { var doubleValue: Double? switch value { case let intValue as Int: doubleValue = Double(intValue) case let stringValue as String: doubleValue = Double(stringValue) default: break // 其他类型直接忽略 } // 只加入有效的数值 if let validValue = doubleValue { separatedValues.append(validValue) } } } // 查看结果 print("分离后的日期列表:\(separatedDates)") print("分离后的数值列表:\(separatedValues)")
适配你现有代码(处理月度数据)
如果你需要在现有处理arrMonthly的代码中加入分离逻辑,可以这样修改:
if let arrMonthly = dictPeriod["monthly"] as? [Any], !arrMonthly.isEmpty { self.arrMonth = NSMutableArray(array: arrMonthly) print("arrMonthly == ", self.arrMonth) // 新增:分离月度数据的日期和数值 var monthlyDates: [String] = [] var monthlyValues: [Double] = [] for item in arrMonthly { guard let monthlyItem = item as? [String: Any] else { continue } // 提取日期 if let date = monthlyItem["date"] as? String { monthlyDates.append(date) } // 提取并转换数值 if let value = monthlyItem["value"] { var doubleValue: Double? switch value { case let intVal as Int: doubleValue = Double(intVal) case let strVal as String: doubleValue = Double(strVal) default: break } if let val = doubleValue { monthlyValues.append(val) } } } // 这里可以使用monthlyDates和monthlyValues做后续处理 print("月度日期:\(monthlyDates)") print("月度数值:\(monthlyValues)") } else { self.arrMonth = NSMutableArray() }
关键说明
- 为什么用
Double存储数值?因为你的数据里value既有整数(如12)又有字符串格式的小数(如"14.5"),转成Double可以统一类型,方便后续的计算或UI展示。 - 加入
guard let做类型校验,是为了避免类型不匹配导致的崩溃,让代码更健壮。 - 如果你的日期需要转成
Date类型(比如做日期排序),可以再用DateFormatter做转换,比如:let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd" if let dateString = weeklyItem["date"] as? String, let date = dateFormatter.date(from: dateString) { // 这里得到的是Date类型的日期 }
内容的提问来源于stack exchange,提问作者Shriram Kadam
相关产品推荐
相关产品推荐

