【问题标题】:Dealing with tuples of different types in json in Swift在 Swift 中处理 json 中不同类型的元组
【发布时间】:2017-10-10 01:34:52
【问题描述】:

我想保存一个元组数组,其中一个元素是值,另一个元素是 Swift 3 中的日期。

这是一些硬编码示例。

var currentDateTime = NSDate()

var confArray: [(conf: Int, date: NSDate)] = []

confArray.append((4, currentDateTime.addingTimeInterval(60 * 60 * 24 * -15)))
confArray.append((3, currentDateTime.addingTimeInterval(60 * 60 * 24 * -7)))
confArray.append((3, currentDateTime))
confArray.append((1, currentDateTime.addingTimeInterval(60 * 60 * 24 * 1)))
confArray.append((5, currentDateTime.addingTimeInterval(60 * 60 * 24 * 2)))
confArray.append((3, currentDateTime.addingTimeInterval(60 * 60 * 24 * 3)))

但是,JSON 似乎不允许元组,并且在我执行此类操作时会引发错误。

let trackingContent = ["key": confArray ]
let jsonData = try JSONSerialization.data(withJSONObject: trackingContent, options: JSONSerialization.WritingOptions())

有没有办法解决这个问题?

我考虑过将这两个元素都转换为字符串并将它们保存为字符串数组。但是,将 Date 转换为 String 需要多行,我必须将其转换回来。 请让我知道是否有更有效的方法将元组存储在 JSON 中,或者我是否遗漏了一些东西。谢谢!

【问题讨论】:

  • 为什么要使用数组类型?我的建议是将confArray 转换为[Int: [NSDate]]
  • 您也可以使用时间戳 (timeIntervalSince1970) 代替 NSDate。它可以很容易地转换回日期
  • @DaoNguyen int 值不是唯一的,因此它必须是 [NSDate: Int][[Int: NSDate]]。是否有可能在不知道第二种情况下的值的情况下获得日期?我需要订购 confArray,以便我可以访问第 3 个元素中的日期、第 5 个元素中的值等。
  • @Woof 谢谢!使用 timeIntervalSince1970 是有意义的。我正在考虑使用 Date 而不是 NSDate,但如果我必须在 String 和 NSDate 之间切换,NSDate 似乎更好。
  • @DaoNguyen 在使用 JSON 时,您不能使用 Int 作为字典键,它必须是字符串。

标签: json swift date tuples


【解决方案1】:

让我们一起玩耍吧!

import Foundation

typealias Conf = (idx: Int, interval: TimeInterval)
typealias JSConf = [String]

extension Array where Element == Conf {
    func encode() -> JSConf {
        return map { "\($0.idx):\($0.interval)" }
    }

    static func decode(_ jsConf: JSConf) -> [Conf] {
        return jsConf.map({ e -> Conf in
            let comps = e.components(separatedBy: ":")
            return (Int(comps.first!)!, Double(comps.last!)!)
        })
    }
}

var confs: [Conf] = []
confs.append((4, 60 * 60 * 24 * -15))
confs.append((3, 60 * 60 * 24 * -7))
confs.append((3, 0))
confs.append((1, 60 * 60 * 24 * 1))
confs.append((5, 60 * 60 * 24 * 2))
confs.append((3, 60 * 60 * 24 * 3))

let encode = confs.encode()

let data = ["key": encode]
do {
    let _ = try JSONSerialization.data(withJSONObject: data, options: JSONSerialization.WritingOptions())
} catch {
    print(error.localizedDescription)
}

let decode = [Conf].decode(encode)

print(decode)

希望对您有所帮助!

【讨论】:

  • 哇,谢谢!我只是将时间间隔切换到 timeIntervalSince1970 而不是从现在开始的时间,我认为这正是我想要的!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-08-02
  • 1970-01-01
  • 2014-03-16
  • 2018-01-23
  • 2018-12-25
  • 2018-07-01
  • 2018-09-07
相关资源
最近更新 更多