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

Swift中XCTAssertEqual比较Date值:如何设置精度?

单元测试中指定精度比较Date值的解决方案

在日期单元测试场景中,编写代码后触发报错:No exact matches in call to global function 'XCTAssertEqual'。核心问题是XCTAssertEqual的accuracy参数类型不匹配——泛型要求该参数需与Date类型一致,但无法创建符合要求的精度Date参数。

测试代码如下:

let day = StockMarketDay(year: 2022, month: 1, day: 4)

let formatter = ISO8601DateFormatter()      // no timezone
formatter.formatOptions = [.withFullDate]
let targetDate = formatter.date(from: "2022-01-04")!
let timeAccuracy = TimeInterval(60*60*24)
let dateAccuracy = Date(timeIntervalSince1970: timeAccuracy)
print("dateAccuracy - \(dateAccuracy)")
// XCTAssertEqual(day!.date, targetDate, accuracy: dateAccuracy) // Error
XCTAssertEqual(day!.date, targetDate, accuracy: timeAccuracy) // Error

解决方法

针对Date类型的精度比较,XCTAssertEqual有专门的重载方法,accuracy参数需传入TimeInterval类型的秒数值,而非Date对象。修改后的断言代码如下:

XCTAssertEqual(day!.date, targetDate, accuracy: 24 * 60 * 60)

关键说明

  • 编译器报错是因为误匹配了泛型重载版本,专门用于Date比较的重载方法签名为:
    func XCTAssertEqual(_ expression1: @autoclosure () throws -> Date, _ expression2: @autoclosure () throws -> Date, accuracy: TimeInterval, file: StaticString = #filePath, line: UInt = #line)
    
  • 只要accuracy参数明确为TimeInterval类型(比如直接写86400或24*60*60),编译器就能正确识别该重载,完成按指定精度比较两个Date的逻辑。

内容的提问来源于stack exchange,提问作者David

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 15:25:09