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

使用Switch Case处理上传日期显示时Int比较报错求助

关于Swift Switch处理时间差的错误解释与解决方案

嘿,我来帮你拆解这个问题~

首先,先解释你遇到的错误:Expression pattern of type 'Bool' cannot match values of type 'Int'。

你写的case timeDifference < 60:本质上是一个布尔表达式(它的结果是true或false),但你的switch是针对Int类型的timeDifference进行匹配的。Swift的switch默认要求case里的模式类型要和switch变量的类型一致——你不能用一个布尔值去匹配整数,这就好比拿苹果去匹配橘子,类型不兼容,所以编译器报错了。

正确的Switch实现方式

Swift其实支持在switch里实现比较逻辑,主要有两种写法:

1. 区间模式匹配

直接用整数区间来定义case的范围,非常直观:

// 先处理targetDate在未来的情况(时间差为负)
guard let timeDifference = Calendar.current.dateComponents([.second], from: targetDate, to: Date()).second, timeDifference >= 0 else {
    print("未来时间")
    return
}

switch timeDifference {
case 0..<60:
    print("刚刚")
case 60..<3600:
    print("\(timeDifference / 60)分钟前")
case 3600..<86400:
    print("\(timeDifference / 3600)小时前")
default:
    print("\(timeDifference / 86400)天前")
}

这里用0..<60表示大于等于0、小于60的整数区间,完美匹配Int类型的timeDifference。

2. 使用where分句添加条件

如果需要更灵活的条件,可以给case加上where分句来过滤:

guard let timeDifference = Calendar.current.dateComponents([.second], from: targetDate, to: Date()).second, timeDifference >= 0 else {
    print("未来时间")
    return
}

switch timeDifference {
case _ where timeDifference < 60:
    print("刚刚")
case _ where timeDifference < 3600:
    print("\(timeDifference / 60)分钟前")
case _ where timeDifference < 86400:
    print("\(timeDifference / 3600)小时前")
default:
    print("\(timeDifference / 86400)天前")
}

_表示匹配任意值,然后通过where来附加判断条件,这样就能实现你想要的比较逻辑了。

替代方案

如果觉得switch写起来麻烦,也可以用更直观的if-else链:

guard let timeDifference = Calendar.current.dateComponents([.second], from: targetDate, to: Date()).second, timeDifference >= 0 else {
    print("未来时间")
    return
}

if timeDifference < 60 {
    print("刚刚")
} else if timeDifference < 3600 {
    print("\(timeDifference / 60)分钟前")
} else if timeDifference < 86400 {
    print("\(timeDifference / 3600)小时前")
} else {
    print("\(timeDifference / 86400)天前")
}

另外,关于“截断时间值”,其实上面代码里的整数除法(比如timeDifference / 60)已经自动完成了截断(向下取整),不需要额外处理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 09:02:57