swift - Switch case to change between "hours ago" or "days ago" for an upload date, comparing an Int value returns an error
问题描述
I'm trying to use a switch case to format an upload date. The way I'm doing it is by converting the time between the upload time and the current time into seconds and then switching between them depending on whether they are greater than a value, 60 being for a minute etc.
switch timeDifference {
case timeDifference < 60:
Time difference is an Int and the 60 is the number that it is being compared to.
For reference, this is how I get that value.
timeDifference = Calendar.current.dateComponents([.second], from: targetDate, to: Date()).second
However, when doing this, it returns an error stating that it can't compare an Int.
Expression pattern of type 'Bool' cannot match values of type 'Int'
I don't fully understand what this error means so an explanation of that would be appreciated, but looking at other questions like this, it is possible to do a comparison in a switch case.
The other option is to truncate the value to something more manageable but I'm not sure how to do that as time values aren't base 10. Or I simply do if-else.
解决方案
Your case
value is a Boolean expression, and that can't be matched with an Int
.
If you really want to do the comparison, then use a where
clause:
switch timeDifference {
case let t where t < 60:
// do something
As @MartinR suggested in the comments, you might be better served by using Interval Matching:
switch timeDifference {
case 0..<60:
// do something
推荐阅读
- c# - C# await Task.Delay 不能按预期使用 WinForms/Selenium
- python - fillna pandas 不会影响原始数据框
- machine-learning - 训练 CNN 时的奇怪损失函数行为
- json - 在 Go 中解组嵌套的自定义同类型 JSON
- python - 如何使用来自其他两个数据框的行创建数据框?
- amazon-web-services - 将 Github Enterprise 与 AWS Codepipeline 集成
- compiler-construction - 无法在 lex 中包含 c++ 库
- node.js - 如何限制 serverless lambda 函数
- r - 如何将我的 GARCH 模型拟合到 R 中的时间序列?
- angular - 使用 Angular 6 指令在组件上设置属性