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

Swift中@AppStorage存Date做API刷新校验时比较始终返回true问题咨询

问题根因

你遇到的始终返回true的问题核心出在两个地方:

  • Date扩展的RawRepresentable实现不稳定:你用timeIntervalSinceReferenceDate.description转字符串存储,description输出的格式会受系统Locale、版本影响,部分场景下会出现科学计数法、逗号代替小数点的情况,导致Double(rawValue)转换失败,最终 fallback 到0.0,对应日期是2001年1月1日。不管你怎么加5秒,这个日期都远早于当前时间,所以判断永远命中currentTime > readyToBeRefreshed分支,返回true。
  • 刷新后的赋值逻辑错误:满足刷新条件后,你是给原lastTimeUserRefreshedApi加5秒,而不是更新为当前时间。如果用户间隔远大于5秒才触发刷新,加5秒后的时间依然早于当前时间,下次调用还是会返回true。

修复方案

第一步:修正Date的RawRepresentable实现

改用timeIntervalSinceReferenceDate的Double值直接转字符串,不要用description,避免格式不稳定问题:

extension Date: RawRepresentable {
    public var rawValue: String {
        String(timeIntervalSinceReferenceDate)
    }
    
    public init?(rawValue: String) {
        guard let timeInterval = Double(rawValue) else { return nil }
        self = Date(timeIntervalSinceReferenceDate: timeInterval)
    }
}

第二步:简化判断逻辑,修正赋值

可以直接一行完成判断,同时更新存储的时间:

@AppStorage("lastTimeUserRefreshedApi") var lastTimeUserRefreshedApi: Date = Date()

func canUserRefreshAPI() -> Bool {
    let canRefresh = Date().timeIntervalSince(lastTimeUserRefreshedApi) >= 5
    if canRefresh {
        lastTimeUserRefreshedApi = Date()
    }
    return canRefresh
}

如果你的业务需要固定间隔是从上次允许刷新的时间开始算,而不是上次实际刷新的时间,再保留原有加5秒的赋值逻辑即可。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 08:36:00