You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift Date往返序列化反序列化后相等性校验失败的问题咨询

Swift Date往返序列化反序列化后相等性校验失败的问题咨询

我最近在写Swift测试的时候遇到了一个奇怪的问题:明明看起来完全一样的两个Date对象,用#expect直接比较相等性就是不通过。下面是我的测试代码:

import Foundation
import Testing

struct TestGrouping {
    @Test func formattingWorks() async throws {
        let dateFormatter = ISO8601DateFormatter()
        let curDate = Date.now
        let date: Date = dateFormatter.date(
            from: dateFormatter.string(from: curDate))!

        #expect(curDate == date)
    }
}

测试套件返回的结果显示两个日期的打印值完全一致,但校验就是失败了:

߈  Test formattingWorks() started.
ࢄ  Test formattingWorks() recorded an issue at TestFormatting.swift:21:9: Expectation failed: (curDate → 2024-11-03 17:28:27 +0000) == (date → 2024-11-03 17:28:27 +0000)
ࢄ  Test formattingWorks() failed after 0.006 seconds with 1 issue.
ࢄ  Suite TestGrouping failed after 0.006 seconds with 1 issue.
ࢄ  Test run with 1 test failed after 0.006 seconds with 1 issue.

后来我把#expect语句改成了比较时间戳,补上了缺失的括号:

#expect(curDate.timeIntervalSince1970 == date.timeIntervalSince1970)

这时候才发现,这两个Date对象的实际时间戳其实是不一样的:

ࢄ  Test formattingWorks() recorded an issue at TestFormatting.swift:18:9: Expectation failed: (curDate.timeIntervalSince1970 → 1730655168.151483) == (date.timeIntervalSince1970 → 1730655168.0)

我也尝试过给dateFormatter设置时区:dateFormatter.timeZone = TimeZone.current,但问题还是存在。

想请教一下,我该怎么做才能让Date对象在序列化反序列化的往返过程中保持真正的相等呢?

备注:内容来源于stack exchange,提问作者wirrbel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.15 08:45:27