从一个字符串中拆分两个日期 Swift

Split Two Dates from One String Swift

我有一个按钮,当用户按下它时,它会使用事件的开始日期和结束日期将事件的日期保存到他们的日历中。

此开始日期和结束日期是从 json 响应中加载的,但这两个日期都是在一个字符串中收到的。

我收到的响应格式是这样的:

{
   "events":[
      {
         "date":"5/12/2021 - 5/14/2021",
      },
      {
         "date":"6/22/2021 - 6/25/2021",
      }
       ]
}

为了正确保存到日历,我需要将开始日期和结束日期与格式如下的字符串分开:“MM/DD/YYYY - MM/DD/YYYY”,以便字符串中的第一个日期是一个名为 startDate 的变量,第二个日期是一个名为 endDate 的变量。

如果我硬编码两个“虚拟”数组,我能够解析 json 响应并且按钮工作正常,但是一旦我收到这个“MM/DD/YYYY - MM/DD/YYYY"?

这应该适合你:

struct Response: Codable {
    let events: [Event]
}

struct Event: Codable {
    let date: String
    
    let startDate: Date
    let endDate: Date
    
    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        date = try container.decode(String.self, forKey: .date)
        
        let splitted = date.components(separatedBy: " - ")
        
        guard let startDateString = splitted.first,
              let endDateString = splitted.last else {
            throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: [], debugDescription: "'date' should follow the format 'DATE1 - DATE2'"))
        }
            
        let formatter = DateFormatter()
        formatter.locale = Locale(identifier: "en_US_POSIX")
        formatter.dateFormat = "M/dd/yyyy"
            
        guard let extractedStartDate = formatter.date(from: startDateString),
              let extractedEndDate = formatter.date(from: endDateString) else {
            throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: [], debugDescription: "The provided dates are not in the correct format M/dd/yyyy"))
        }
        startDate = extractedStartDate
        endDate = extractedEndDate
    }
}

以及从您的 json 解析它的示例:

let json = """
{
   "events":[
      {
         "date":"5/12/2021 - 5/14/2021",
      },
      {
         "date":"6/22/2021 - 6/25/2021",
      }
       ]
}
"""

let response = try JSONDecoder().decode(Response.self, from: json.data(using: .utf8)!)
print(response.events)