首页 > 解决方案 > 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.

标签: swiftswitch-statement

解决方案


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

推荐阅读